C++ Rules for Constructors and Destructors
C++ constructors and destructors work automatically to guarantee the
appropriate creation and removal of a class instance. The following features and rules
apply to C++ constructors and destructors:
Constructors:
- The name of the constructor must be identical to the name of the class.
- You must not include any return type, not even void!
- A class can have any number of constructors, including none. The compiler automatically
creates a constructor for a class that has none.
- The default constructor is the one that either has no parameters or it has
a parameter list in which all the parameters use default arguments.
- The copy constructor enables you to create a class instance using an existing
instance. If you do not declare a copy constructo, the compiler creates on for you.
The compiler creates a shallow copy constructor. This constructor simply copies
data members. If your class includes dynamic data (using new, for example)
you need to write your own copy constructor to do a deep copy including dynamic
data structures.
- The instantiation of a class (declaring an instance of the class) involves
a constructor. Which constructor is called depends on how many constructors you have
declared and you declared the class instance. For example, instantiation with no arguments
will call the default constructor.
Destructors:
- The name of the destructor must begin with the tilde character (~).
The rest of the destructor name must be identical to the name of its class.
- You must not include any return type, not even void!
- A class can have no more than one destructor. If you omit the destructor, the compiler
automatically creates one for you.
- The destructor cannot have any parameters.
- The class destructor is automatically invoked when the instance of that class goes out of scope.