You are on page 1of 12

Constructor & Destructor

P VASUKI
CONSTRUCTOR
• It is a member function which initializes a
class.
• It is invoked when during object
instantiation
• A constructor has:
(i) the same name as the class itself
(ii) no return type
• If constructor is not defined in the
program the compiler creates default
constructor
CONSTRUCTOR
Class point
{
int x;
int y;
point() //constructor
{
x = 0;
y = 0;
}
Types of Constructor

• Default /constructor
–Ex: point()// Doesn’t take any
parameter
–Invoked as point p;
• Parameterized constructor
• Copy Constructor
Parametrized Constructor
A class can have many parameterized constructor
• Compiler choose appropriate match during
compilation process)
• Generally used to initialize data members with
the values passed as parameters
– point(int a, int b){ x= a; y=b)
– point(int w){ x=y= w}
– Point(float i, float j) (x = (int) j; y = floor(j)
}
– point (int m =3)
• No two constructor should match in signature
– Point(x=y=0) point(int p=3){x=y=p} is not
allowed
Copy Constructor
• It is a member function which initializes an
object using another object of the same class.
• A copy constructor has the following general
function prototype: class_name
(const class_name&);
• If copy constructor is not defined, the constructor
generates copy constructor and got invoked when
= operator is invoked.
• The compiler generated copy constructor works
perfect except initializing the pointer member
variable.
Need for Copy Constructor
• class string
{ private:
char *s;
int size;
public:
string(char *); // constructor
print();
void copy(char *);
};
Need for Copy Constructor -
contd
void string::print()
{ cout << s << endl; }
void string::copy(char *c)
{ strcpy(s, c); }
Need for Copy Constructor -
contd
void main()
{
string str1("George");
string str2 = str1; // default copy constructor
str1.print(); // what is printed ?
str2.print();
str2.copy("Mary");
str1.print(); // what is printed now ?
str2.print();
}
Copy Constructor - Example
• string::string(const string& old_str)
{
size = old_str.size;
s = new char[size+1];
strcpy(s,old_str.s);
}
Destructor
• It is a member function which deletes an object.
• A destructor function is called automatically
when the object goes out of scope:
(1) the function ends
(2) the program ends
(3) a block containing temp. variables ends
(4) a delete operator is called
• A destructor has:
(i) the same name as the class but is preceded by a tilde (~)
(ii) no arguments and return no values
Destructor
• If explicit destructor is not defined,
compiler generates a default
destructor
• When a class acquires any shared
resource (Example pointer of a
variable got memory allocated), the
destructor has to release
it.(deallocates the memory)

You might also like