Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize private data items of the related class. Following are the main features of constructors. Ø Constructor has the same name as is the name of class. Ø Constructors do not have any return type. Ø Constructors are usually declared in public section of the class so that they can be invoked outside the class, when an object is created. Ø Constructors can be private also but private access modifier will hide that constructor from outside the class. Private constructors can be called in class itself and in friend functions only. Ø There can be more than one constructors in a class known as constructor overloading. Ø In case no constructor is defined a default constructor is executed by the compiler. Default customer do not take any parameter. Ø Constructor defined by the programmer may or may not take the parameters. Ø Constructors can also be defined as inline. Ø Constructors can have any type of arguments except its own class type. But the constructor can accept a reference to its own class type object as a parameter. Ø We cannot refer to their address. Program 1: simple constructor with parameters // program to demonstrate how to write and use a constructor #include <iostream> using namespace std; class Recharge int customer_id, amount, validity; ; Recharge (int, int, int); //constructor declared void disply(); // definition of constructor outside the class Recharge :: Recharge (int a, int b, int c) customer_id = a; amount = b; validity = c; Recharge void :: display () cout<< \n...account information of customer... ; cout<< \n customer_id : <<customer_id;
cout<< n amount paid : << amount; cout<< \n validity for : << validity << no. of days ; int main () Recharge cust1( 103, 400, 30); // constructor invoked // implicitly Recharge cust2(205, 200, 10); cust1.disply( ); cust2.display( );...account information of customer... customer_id : 103 amount paid : 400 validity for : 30...account information of customer... customer_id : 205 amount paid : 200 validity for : 10 Types of constructors v Default constructor v Parameterized constructor v Copy constructor Default constructor Any constructor without parameters or when all the parameters have default values is known as a default constructor. It can be auto generated or user defined, but in both the cases it must be called without parameters. If no constructor is defined by the programmer then the compiler implicitly creates a default constructor without body i.e. without any corresponding statement. If there are non-default constructors in the program, then the compiler does not create default constructor. There it is the responsibility of programmer to define default constructor otherwise an error may get generated. Any class can have at the most one default constructor. Default constructors are also known as implicit constructor. Program 2: default constructor with default parameters // program to demonstrate default constructor #include<iosteram> #include<math> class cal_power int n, p; // to use pow() function cal_power ( int a = 10, b = 2); /* default constructor with default arguments*/
void display_result( ) << = << pow(n,p); ; cout<< \n <<n<< raised to the power << p // definition of default constructor --- outside the class cal_power :: cal_power( int a, int b) n = a; p = b; int main ( ) cal_power c1; C1.display_result( ); /* object c1 created using default constructor */ 10 raised to the power 2 = 100 Parameterized constructor This type of constructors are defined with list of arguments. Values for arguments are assigned at the time of creating the objects. Program 1 demonstrates the parameterized constructors. The parameterized constructor can be called implicitly or explicitly, for example v customer_id c1(555, 250, 20); //constructor called implicitly v customer_id c2 = customer_id(111, 300, 21); // constructor called explicitly Copy constructor Copy constructor is used to declare and initialize an object from some already existing object of the class. As discussed above constructors can have any type of arguments except its own class type. But the constructor can accept a reference to its own class type object as a parameter. Copy constructor takes a reference to the object of same class as an argument. Copy constructor cannot accept argument by value. Syntax for copy constructor Example Class_name (class_name & object_name)...body of constructor... Example: customer_id ( customer_id & c ); if there exists a statement like: customer_id cus1( 100,500,25); then following are valid statements to initialize cus2 and cus3 with cus1 customer_id cus2( cus1); customer_id cus3 = cus1;
Constructor overloading A program can have multiple constructors and this concept is called constructor overloading. Program 3: to demonstrate copy constructor and constructor overloading /*C++ program to demonstrate example of Copy Constructor.*/ #include <iostream> using namespace std; class demo private: int X; int Y; ; demo () demo (int a, int b); demo (const demo &d); void display(); //Definition of parameterized constructor. demo:: demo(int a, int b) X = a; Y = b; //Definition of copy constructor. demo:: demo(const demo &d) X = d.x; Y = d.y; // default constructor //parameterized constructor //copy constructor //Definition of display (),the member function. void demo:: display() cout <<"\n X: " << X; cout <<"\n Y: " << Y; int main() demo d1(10,20) ; // creates an object cout<< \n data members of the created object ; cout << \n Object d1 : "; cout<<"values initialized by parameterized constructor: "; d1.display(); /* create and initialize object with other object using copy constructor */
demo d2 = demo(d1); cout<< \n\n object d2, created by copy constructor ; cout << \n Object d2 : " ; cout << "Value initialized by copy constructor : "; d2.display(); data members of the created object Object d1 : Values initialized by parameterized constructor: X: 10 Y: 20 object d2, created by copy constructor Object d2 : Value initialized by copy constructor: X: 10 Y: 20 Copy constructor is used to Ø To initialize an object using another object Ø To copy an object to pass it as an argument by value to a function Ø Also to copy the object to return it from a function by value. Note: If no copy constructor is defined in the class then compiler generates a default copy constructor at its own. Program 4: to demonstrate, when a copy constructor is called by the compiler // program to find sum of two complex numbers #include<iostream> class complex int real, img; complex() // default constructor complex(int r, int i) //parameterized constructor real = r; img = i; complex (complex &c) // copy constructor cout<< \n hi! I m copy constructor here ; real = c.real; img = c.img;
complex sum(complex c); // object as return type void display( ); ; // end of class definition complex complex :: sum(complex c) complex temp; // temporary object created temp.real = real + c.real; temp.img = img + c.img /* real and img in above statements hold data values for the calling object */ return (temp) // returns temp object void complex :: display( ) cout << \n complex number : << real << \t + \t << img i ; //... main function... int main( ) complex c1(5,4); complex c2 = c1; // parameterized constructor invoked //invokes copy constructor // invokes default constructor complex c3; c3 = c1. sum (c2); // please see the note below c1.display( ); c2.display( ); c3.display( ); Note: explanation of statement c3 = c1. sum (c2); Ø Copy constructor is invoked twice in this single statement. Ø c1 is active object here, hence its private data items (real and img) will be used directly i.e without object name and. operator, in the member function sum. Ø c2 is actual argument passed by value to the function. Copy constructor is invoked here to create a copy of c2, the compiler itself calls the copy constructor to create the copy of passed object c2. Ø Compiler once again calls the copy constructor when it encounter the, return(temp); statement in the end of sum function. Here compiler creates unnamed object to hold the value of returned object. hi! I m copy constructor here hi! I m copy constructor here hi! I m copy constructor here complex number : 5 + 10 i
complex number : 5 + 10 i complex number : 10 + 20 i Destructor Destructor functions are inverse of constructor functions. They are invoked automatically when objects are destroyed. An objects gets destroyed when its scope of existence finishes or when the delete operator is used. Like constructor, destructor also follows some rules: Ø Destructors are special member functions of the class and they are used to free the memory allocated to object. Ø Destructors are functions with same name as class and they do not accept any parameters. Even constructors have same name as class, but name of destructor is preceded by ~ (tilde). Ø Like constructor, destructors do not have any return type. Not even void Ø The Destructor of class is automatically called when the object goes out of scope. Ø If there exists no user defined constructor in a class, but is required then the compiler itself declares a destructor implicitly. Ø Destructors cannot be inherited. (will be discussed later) Program 5: to demonstrate the destructor function, how is destructor function declared, defined and invoked /* program to illustrate, automatic execution of constructor and destructor */ #include<iostream> using namespace std; class test char code; test( char c) // constructor defined created ; code = c; cout<< \n object with code = << code << is ~ test ( ) // destructor defined cout<< \n object with code = <<code<< is destroyed ; ; // end of class int main( ) test obj(a), obj(b), obj(c); cout<< \n three object created ; cout<< \n the main program ends here ;
object with code = a is created object with code = b is created object with code = c is created three object created the main program ends here object with code = a is destroyed object with code = a is destroyed object with code = a is destroyed Note: Ø Constructor function is called three times because, three objects are created in first statement of main function. Ø Statements of the main function get executed in the order these are written. Ø Destructor function is called three times (once for each object) just before exiting from the main function.