C++ Programming - Constructors and Destructors
by Wrox Books
While any code may appear in the constructor and destructor it is recommended that code relating to initialising data members in the class be implemented in the constructor. A destructor will perform destroy any dynamic memory that was allocated in the constructor or at some other point in the object life, as well as releasing any system resources that might similarly have been assigned to the object during its life.
Constructors always have the same name as their class. Destructors take the name of their class preceded by a tilde (~).
A class may have more than one constructor.
A class may not have two constructors that agree in terms of the number and type of their parameters.
Constructor and destructors are usually defined as public members of their class and may never possess a return value. They may however sometimes be protected so that code outside the class heirarchy can not construct objects of that class.
Example:
#include <string.h>
#include <iostream.h>
class MyClass
{
private:
int myInt;
char myText[20];
//
public: // destructors must be public member functions
MyClass() // constructor with no parameters - the 'default'
{
myInt = 0;
myText[0]='\0'; // null string
}
MyClass(const MyClass &anObjectOfMyClass) // 'copy' constructor
{
myInt = anObjectOfMyClass.myInt;
myText = anObjectOfMyClass.myText;
}
/* if assignment were defined for this class then the
body of the copy constructor could be defined as follows:
{ *this = anObjectOfMyClass;}
*/
MyClass(const int thisint, const char* thattext = 0)
:myInt(thisint)
{
strcpy(myText,thattext);
}
~MyClass() // destructor: NB no parameters
{ // destructor code
}
// a friend for output:
friend ostream& operator <<(ostream&, MyClass &);
}; // end of class declaration
ostream& operator <<(ostream & os,MyClass &anObjectOfMyClass)
{
os << anObjectOfMyClass.myInt << "+ " << anObjectOfMyClass.myText
<< "+";
return os;
}
void main(void)
{
MyClass mcObj1; // default constructor
MyClass mcObj2(1,"abcde"); // with parameters
MyClass mcObj3(mcObj2); // copy constructor
MyClass mcObj4 = mcObj3; // copy constructor called
// by initialisation
cout << "mcObj1 : " << mcObj1 << endl;
cout << "mcObj2 : " << mcObj2 << endl;
cout << "mcObj3 : " << mcObj3 << endl;
cout << "mcObj4 : " << mcObj4 << endl;
return;
}
...produces as output:
mcObj1 : 0+ +
mcObj2 : 1+ abcde+
mcObj3 : 1+ abcde+
mcObj4 : 1+ abcde+
Naturally the functions can be declared in the class body, and defined elsewhere as usual. For example:
MyClass::MyClass()
{
// etc.
}
MyClass::~MyClass()
//
}
A constructor allocates space for an object and ensures that it is initialised correctly.
Default Behaviour
If a class is straightforward, then there may be no need to worry about constructors and a destructor at all.
If no default constructor is defined then the action on creation is to allocate store for member objects; if default constructors are defined for these member objects then these constructors will in turn be called and the member objects will be initialised. If the member objects are of primitive data types then initialisation will be contingent upon their storage class.
The function of the default copy constructor is simply to make bitwise copies of all member data. This is correct if all the data relevant to the class is held within it, but is possibly useless and certainly dangerous if references and pointers are involved.
If the copying involves the copying of an address, then two objects will appear to have two different data members with the same ultimate (de-referenced) value, whereas in reality they are both pointing at the same store: changes made through one will be reflected in the other and vice versa.
Should one decide to delete the data concerned, then the other will be left with a pointer to nowhere (a ' dangling ' pointer). Strategies exist to cope with this, involving keeping track of the number of pointers to an object, but usually involve overloading the reference operators and are not for the faint-hearted. In general, it is better to avoid this situation altogether.
Initialisation List
Notice the use of the initialisation list in the declaration:
MyClass(const int thisint, const char* thattext):myInt(thisint)
This states that the value thisint is to be passed to the constructor for myInt. This is a primitive type so there is no real concept of a constructor but the effect is the same. Obviously if a user-defined type is involved then this will cause a call to the appropriate constructor.
Why bother? Why not just assign values in the body of the constructor? One obvious use is to supply an initialisation for a const item, another is to supply parameters to base classes. If these are not supplied as such, then if data members are private it will be necessary to call member functions to assign them values: a tedious task. In any event, it will be more efficient to execute the single stage process of initialisation than the two stage process of initialisation followed by assignment. Note that the order of initialisation of members is the order declared in the class, not the initialisation list. This is of importance when the value of one member is used in the initialisation of another.
Note that out of line constructors have the initialisation list in the function definition, not the class definition. Note also that if any constructor is defined, then calls to the default parameterless constructor will fail unless such a constructor has explicitly been defined.
Destructors
Destructors are used to control the behaviour of an object when it passes out of scope or is otherwise to be discarded. If the class is simple then a destructor may not be necessary: the default is simply to discard the store occupied by the data members. However, if pointers are involved, then you must explicitly delete objects pointed to so that memory leakage does not occur.
As a rule of thumb, define a destructor, even if it does nothing: it may be useful later. A second rule is that a destructor for a class that is likely to be a base class for other derived classes should always be virtual. This allows the correct destructor to be called if an object is deleted via a base class pointer: otherwise the destructor for the base class will be called, with the wrong results. ( Note the opposite is not permissible; constructors may never be declared as virtual member functions.)
Constructors Destructors and Inheritance
When an object of a derived class is created constructors for the class and for the classes from which it is derived are called. The constructor calls occur in the following order.
1) The constructors of any virtual base classes are called first in the order of inheritance from the ultimate base class to the lowest virtual class in the inheritance hierarchy.
2) If there are any non-virtual base class constructors to be called then these are called next.
3) The derived class constructor is called last.
When an object of a derived class is destroyed the order of destructor calls is the reverse of that for the constructors with the derived class destructor being called first.
Constructors for the derived class may pass the arguments to the constructor for the base.
Example
1. Simple example with constructors/destructor
#include <iostream.h>
class base {
public:
base() { cout << "Constructing base class\n"; }
~base() { cout << "Destructing base class\n"; }
};
class derived : public base {
public:
derived() { cout << "Constructing derived class\n"; }
~derived() { cout << "Destructing derived class\n"; }
};
main()
{
derived obj;
return 0;
}
This gives as output:
Constructing base class
Constructing derived class
Destructing derived class
Destructing base class
2. Here is another example, but passing arguments to the constructors:
#include <iostream.h>
#include <string.h>
class base {
int wheels;
public:
base(int n) { wheels = n; }
int get_wheels() { return wheels; }
};
// Public inheritance of the base class - pass constructor arg n
class car:public base {
char name[20];
public:
car(char * s, int n) : base(n) { strcpy(name, s); }
void show();
};
void car::show()
{
cout << "Car " << name << " has " << get_wheels() << " wheels.\n";
}
main()
{
car xr3("XR3 'Orrid", 4);
xr3.show();
return(0);
}
Note how the argument is passed onto the base constructor:
car(char * s, int n) : base(n) { strcpy(name, s); }
This may be read as, "pass n to base FIRST, then do whatever I need as part of my derived constructor". Note also, that the creation of the object in main() requires passing all the arguments needed by both the base and derived class constructors.
Note also that the derived class constructor does not need to use the argument passed to it - it may simply pass it onto the base class constructor.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Web Development Articles
More By Developer Shed