Constructors & Destructors
Constructors & Destructors
Constructors
rectangle::rectangle(float h, float w)
{
height = h;
width = w;
}
CONSTRUCTOR WITH DEFAULT
ARGUMENTS
Just like functions, constructors can also have
default values for arguments. In this case, if we
are not passing the values for arguments at the
time of creating objects then default value will
be taken up.
Example:
using namespace std;
#include<iostream>
class rectangle
{
int l,b;
public:
rectangle (int x=12,int y=34)
{
l=x;
b=y;
}
int area()
{
return(l*b);
}
};
int main()
{
rectangle r;
cout<<"Area is "<<r.area();
rectangle r1(45,67);
cout<<"\nArea is "<<r1.area();
}
Copy constructor
• A copy constructor is a constructor that
creates a new object using an existing object
of the same class and initializes each data
member of newly created object with
corresponding data member of existing object
passed as argument.
• since it creates a copy of an existing object so
it is called copy constructor.
Example
class counter
{
int c;
public:
counter(int a) //single parameter constructor
{
c=a;
}
counter(counter &ob) //copy constructor
{
cout<<“copy constructor invoked”;
c=ob.c;
}
}
Void show()
{
cout<<c;
};
int main()
{
counter C1(10);
counter C2(C1);// call copy constructor
C1.show();
C2.show();
}
INITIALIZER LIST
• So far we have discussed constructor in which
the initialization is performed in its body.
• Another alternate way is Initializer list
• Initializer list is placed between the parameter
list and opening braces of the body of
constructor.
• When the constructor is declared inside and
defined outside the class using scope resolution
then the member initialization list can only be
specified within the constructor definition and
not its declaration.
• An list allows initialization of data members
at the time of the creation which is more
efficient as values are assigned before the
constructor even starts to execute.
• rectangle(int a,int b):length(a),breadth(b){…}
Example of initializer List
using namespace std;
#include<iostream>
class rectangle
{
int l,b;
public:
rectangle (int x,int y):l(x),b(y){}
int area()
{
return(l*b);
}
};
int main()
{
rectangle r(12,34);
cout<<"Area is "<<r.area();
}
What is a copy constructor?
a) Error occurs
b) Segmentation fault
c) Objects are not created properly
d) Compiler provides a dummy constructor to
avoid faults/errors
How many parameters does a default
constructor require?
a) 1
b) 2
c) 0
d) 3
Destructors
• A destructor doesn`t have a return type, not even void and no arguments
• If you don’t provide a destructor of your own then the compiler generates
a default destructor