Constructor in C++

Constructors in C++

A constructor in C++ is a special member function whose task is to initialize the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows: class integer //class with a constructor { private: int m, n; public: integer(); //constructor declared … … }; integer :: integer() //constructor defined { m = 0; n = 0; } When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialized automatically. For example, the declaration: integer in1; //object in1 created not only creates the object in1 of type integer but also initializes its data members m and...

Why use Constructor and Destructor in C++

We have seen, so far, a few examples of classes being implemented. In all the cases, we have used member functions such as getdata() and setvalue() to provide initial values to the private member variables. For example, the following statement: X.input(); invokes the member function input(), which assigns initial values to the data items of the object X. Similarly, the statement: A.getdata(100,299.95); passes the initial values as arguments to the function getdata(), where these values are assigned to the private variables of object A. All these ‘function call’ statements are used with the appropriate objects that have already been created. These functions cannot be used to initialise the member variables at the time of creation of their objects. This means that we are not able to initialize a class type variable (object) when it is declared, much the same way as initialization of an ordinary variable. For example: int p...