C++

Topic: Constructors and destructors

What are Constructor and Destructor Order ?

The process of creating and deleting objects in C++ is not a trivial task. Every time an instance of a class is created the constructor method is called. The constructor has the same name as the class and it doesn't return any type, while the destructor's name it's defined in the same way, but with a '~' in front: class String{public:String() //constructor with no arguments    :str(NULL),    size(0){}String(int size) //constructor with one argument    :str(NULL),    size(size){    str = new char[size];}~String() //destructor{    delete [] str;};private:    char *str;    int size;} Even if a class is not equipped with a constructor, the compiler will generate code for one, called the implicit default constructor. This will typically call the default constructors for all class members, if the class is using virtual methods it is used to initialize the pointer to the virtual table, and, in class hierarchies, it calls the constructors of the base classes. Both constructors in the above example use initialization lists in order to initialize the members of the class.  The construction order of the members is the order in which they are defined, and for this reason the same order should be preserved in the initialization list to avoid confusion.  To master developing and debugging C++ applications, more insight is required regarding the way constructors and destructors work. Some problems arise when we are dealing with class hierarchies. Let's take a look at the following example where class B is inherited from class A: class A{public:A(int m,int n)    :m(m),    n(n){    cout<<"constructor A"<<m<<n;};~A(){};private:int m;int n;};class B : public A{public:B()    :b(5) //error : default constructor to initialize A is not found{    cout<<"constructor B"<<b;}~B(){};private:int b;};int main(){B x;return 0;}; When we create an object of type B, the A part of the B object must be initialized and since we provide a constructor for class A, the compiler will not create an implicit default constructor. This code will fail to compile because there is no default constructor for class A to be called. To fix this we could provide a default constructor in class A or explicitly call the existing constructor of A in the initialization list of the B's constructor: B():A(3,4),b(5){    cout<<"constructor B"<<b;} Notice that we needed to call the constructor of A before doing any initialization in B, since the order of construction starts with the base class and ends with the most derived class.

Browse random answers: