Sie sind auf Seite 1von 21

Constructors and Destructors

Constructors
• When a variable of built in data type goes out of
scope, the compiler automatically destroys the
variable.
Int i= 10;
char c= ‘a’;
But this does not happen in case of objects.
• So, C++ provides a special member function
called the constructor which enables an object
to initialize itself when it is created.
• This is known as automatic initialization of
objects
Contd..
•“A constructor is a special member function whose task is to
initialize the objects of its class.”
•Its name is same as that of the class.
•It is invoked whenever an object of its associated class is created.
•Example:
Class sum //constructor defined
{ sum::sum(void)
inti, j; {
i=10;
public:
j=20;
sum(void);
}
//constructordeclared sums1; //objects1created
};
Default Constructor
• A constructor that accepts no parameters is called
the default constructor.
• The default constructor for class A is
A::A( )
• If no such constructor is defined, then compiler
itself supplies a default constructor.
• So, a statement such as
A a;
• Invokes the default constructor of the compiler to
create the object a.
Example
#include <iostream>
using namespace std;
class A
{ public:
A()
{cout<<"Default Constructor called"<<endl;}
};
int main()
{
A a1;
A a2;
return 0;
}
Characteristics
• They should be declared in the public section.
• They are invoked automatically when the objects
are created.
• They do not have return types, not even void,
and so they can not return values.
• They can not be inherited, though the derived
class can call a base class constructor.
• They can have default arguments.
• Constructors can not be virtual.
Parameterized Constructor
• Constructors that take arguments are called
parameterized constructors

sum s1=sum(10,20); //explicit call


sum s1(10,20); //implicit call
Example
class Example
{ // Variable Declaration int main()
int a,b; { Example
Object(10,20);
public:
// Constructor invoked.
Example(int x, int y) //Constructor
Object.Display();
{ a=x;
return 0;
b=y;
}
cout<<"I am Constructor\n“; }

void Display()
{ cout<<"Values
“<<a<<"\t"<<b; }
};
Constructors with default arguments
• It is possible to define constructors with default
arguments
complex (float real, float imag=0);
• The default value of imag is zero.
• So, if called via:
complex C(5.0);
Here, imag is by default 0.0
• If called:
complex C(2.0, 3.0);
Here, imag value will be 3.0, as this value will override
the default value 0.0
Example
class student
int main()
{
{
int roll_no;
student s1;
float marks;
student s2(1,60);
public:
cout<<"Output using default
student(int x=10,float y=40) constructor arguments:\n";
{ s1.display();
roll_no=x; cout<<"Output without default
marks=y; constructor arguments:\n";
} s2.display();
void display() };
{
cout<<"Roll no:"<<roll_no<<endl;
cout<<"Marks:"<<marks<<endl;
}
};
Copy Constructor
• A constructor that can accept a reference to its
own class as a parameter, is called a copy constructor.
• Is used to declare and initialize an object from another
object.
Eg:
sum s2 (s1);
sum s2 = s1;
• The process of initializing through a copy constructor is
known as copy initialization.
• However,
sum s2 = s1; & s2 = s1;
are not same
Contd..
• The statement
s2=s1;
• Will not invoke the copy constructor.
• If s1 and s2 are objects ,this statement is legal
and assigns the values of s1 to s2, member-by-
member.
Example
class abc int main()
{ private: { abc ob1(50,4.5, 'a'); // object created
int a; abc ob2(ob1);
float b; abc ob3=ob2;
char c; cout<<"object 1 data value"<<endl;
public: ob1.display();
abc(int x,float y, char z) cout<<"object 2 data value"<<endl;
{ a=x; ob2.display();
b=y; cout<<"object 3 data value"<<endl;
c=z; ob3.display();
} }
abc(abc &p);// copy contructor
void display()
{ cout<<"a= "<<a<<endl;
cout<<"b= "<<b<<endl;
cout<<"c= "<<c<<endl; }
};
abc:: abc(abc &p)
{
a=p.a;
b=p.b;
c=p.c;
}
Multiple Constructors

• Sum s1;//invoke the first constructor


•Sum s2 (20,30);//invoke the second constructor
•Sum (s2);//invoke the third constructor
•This is called as: Constructor Overloading.
Example
class Area
int main()
{ private:
{
int length; Area A1,A2(10,3);
int breadth; int temp;
cout<<"Default Area when no argument is
passed."<<endl;
public:
Area(): length(5), breadth(2){ } temp=A1.AreaCalculation();
// Constructor without no argument A1.DisplayArea(temp);

Area(int l, int b): length(l), breadth(b){ } cout<<"Area when (10,3) is passed as


// Constructor with two argument argument."<<endl;
void GetLength()
temp=A2.AreaCalculation();
{ cout<<"Enter length and breadth "; A2.DisplayArea(temp);
cin>>length>>breadth;
} return 0;
}
int AreaCalculation() {
return (length*breadth); }

void DisplayArea(int temp)


{ cout<<"Area: "<<temp<<endl; }
};
Dynamic Constructor
• Dynamic constructor is
used to allocate the
memory to the objects
at the run time.
• Memory is allocated at
run time with the help
of 'new' operator.
• By using this
constructor, we can
dynamically initialize the
objects.
Example
class str void str::join(str &a,str &b)
{ {
char *name; len=a.len+b.len;
int len; name=new char[len+1];
public: strcpy(name,a.name);
str() strcat(name,b.name);
{ };
len=0;
name=new char[len+1]; int main()
} {
str(char *s) char *first="INDIA";
{ str n1(first),n2("ASIA"),n3("THAPAR"),n4,n5;
len=strlen(s); n4.join(n1,n2);
name=new char[len+1]; n5.join(n4,n3);
strcpy(name,s); n1.show();
} n2.show();
void show() n3.show();
{ n4.show();
cout<<"NAME IS:->"<<name<<endl; n5.show();
} }
void join(str &a,str &b);
};
Destructor
• It is used to destroy the objects that have been
created by a constructor.
• Its name is same as that of the class but
preceded by a tilde.
~ sum();
• A destructor never takes any argument nor
returns any value.
• It is called implicitly by the compiler upon exit
from the program., to clean up the storage that is
no longer accessible.
Using Destructors
• Destructors are called when one of the following
events occurs:
– An object allocated using the new operator is explicitly
deallocated using the delete operator.
– A local (automatic) object with block scope goes out of
scope.
– The lifetime of a temporary object ends.
– The destructor is explicitly called using the destructor
function's fully qualified name.
Example
int main()
class A {
{public: A obj1; // Constructor Called
A() int x=1;
{ if(x)
cout << "Constructor called"<<endl; {
} A obj2; // Constructor Called
} // Destructor Called for obj2
~A() } // Destructor called for obj1
{
cout << "Destructor called"<<endl;
}
};
Destructor using delete
class B
{
public:
B()
{
cout << "Inside Base constructor" << endl;
}
~B ( )
{
cout << "Inside Base destructor" << endl;
}

};

int main( )
{
B *ob=new B();
delete ob;
}

Das könnte Ihnen auch gefallen