Tutorials All - Webdesign, Graphic Design

Visit our new Webdesign Templates,css,html5 etc

Download New Android Applications

Visit our new Collections of Android Application

1.10.12

Constructors and Destructors in C++


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.
Read More : Click Here