Professional Documents
Culture Documents
C Constructor
C Constructor
int main() {
mca obj1("yasir");
mca obj2("iqbal ");
}
COPY CONSTRUTOR
A copy constructor is a member function that initializes an object using
another object of the same class
• A Copy Constructor creates a new object, which is exact copy of the
existing object. The compiler provides a default Copy Constructor to all
the classes.
Syntax:
class-name (class-name &){}
class lpu
{ public:
int x;
lpu (int a)
{
cout<<"value of a in contructor "<<a; }
lpu (lpu &i)
{ cout<<"value of x in copy constructor"<<i.x; }
};
int main ()
{ lpu a1(40); // Calling the parameterized constructor.
lpu a2=a1; // Calling the copy constructor.
}
• When is a user-defined copy constructor needed?
If we don’t define our own copy constructor, the C++ compiler creates a default
copy constructor for each class
• The compiler created copy constructor works fine in general.
• We need to define our own copy constructor only if an object has pointers or any
runtime allocation of the resource like filehandle, a network connection..etc.
DESTRUCTOR
• A destructor works opposite to constructor
• It destructs the objects of classes.
• It can be defined only once in a class.
• Like constructors, it is invoked automatically.
• A destructor is defined like constructor. It must have same name as
class. But it is prefixed with a tilde sign (~).
• syntax
~classname()
{
}