Introduction To Constructors And Destructors

From Appmethod Topics
Jump to: navigation, search

Go Up to Constructors And Destructors Index

There are several special C++ member functions that determine how the objects of a class are created, initialized, copied, and destroyed. Constructors and destructors are the most important of these. They have many of the characteristics of normal member functions - you declare and define them within the class, or declare them within the class and define them outside - but they have some unique features:

  • They do not have return value declarations (not even void).
  • They cannot be inherited, though a derived class can call the base class's constructors and destructors.
  • Constructors, like most C++ functions, can have default arguments or use member initialization lists.
  • Destructors can be virtual, but constructors cannot. (See Virtual destructors.)
  • You cannot take their addresses:
int main (void)
{
.
.
.
void *ptr = base::base;    // illegal
.
.
.
}
  • Constructors and destructors can be generated by the compiler if they have not been explicitly defined; they are also invoked on many occasions without explicit calls in your program. Any constructor or destructor generated by the compiler will be public.
  • You cannot call constructors the way you call a normal function. Destructors can be called if you use their fully qualified name.
{
.
.
.
X *p;
.
.
.
p->X::~X();                // legal call of destructor
X::X();                    // illegal call of constructor
.
.
.
}
  • The compiler automatically calls constructors and destructors when defining and destroying objects.
  • Constructors and destructors can make implicit calls to operator new and operator delete if allocation is required for an object.
  • An object with a constructor or destructor cannot be used as a member of a union.
  • If no constructor has been defined for some class X to accept a given type, no attempt is made to find other constructors or conversion functions to convert the assigned value into a type acceptable to a constructor for class X. Note that this rule applies only to any constructor with one parameter and no initializers that use the "=" syntax.
class X { /* ... */ X(int); };
class Y { /* ... */ Y(X); };
Y a = 1;                   // illegal: Y(X(1)) not tried

If class X has one or more constructors, one of them is invoked each time you define an object x of class X. The constructor creates x and initializes it. Destructors reverse the process by destroying the class objects created by constructors.

Constructors are also invoked when local or temporary objects of a class are created; destructors are invoked when these objects go out of scope.

See Also