Вы находитесь на странице: 1из 31

Constructor and

Destructor
C++
Constructor: Definition
A constructor is a special member function
which is used to initialize the objects of a class.
Note:-
A constructor is distinct from other member functions
because its name is same as the name of the class.
It is the first member function executed
automatically when an object is created.
The only restriction that applies to constructor is that
it must not have a return type (not even void).
It cannot be inherited, though a derived class can call
the base class constructor.
General syntax of constructor
class classname
{
-------------
-------------
-------------
classname( parameter list);//constructor declaration
-----------------
};
//constructor definition
class name::classname(parameter list)
{
--------
}
EXAMPLE
Example:
class Bank
{
private:
int x,y;
---------
----------
public:
Bank( );
};

Bank :: Bank( )
{
x=0;
y=0;
}
void main()
{
Bank B;
}
When an object B is created ,constructor will be called automatically and it will initialize the
data members x=0 and y=0
NEED FOR A CONSTRUCTOR
A Constructor is used to initialize the
objects of the class being created. So, it
is needed whenever:
1. When you want to initialise the data member
of the class with some default values.
2. When you want to initialise the data
members of the class with arguments
passed to the constructor.
3. When you want to carry out any work when
an object is created.
Where to define
constructor?
Generally constructor will be defined under
public section, which can be available to non
members also.
But it can also be defined under private or
protected.
A private or protected constructor is not available to
the non-member functions.
i.e. With a private or protected constructor, you cannot
create an object of the same class in a non-member
function.
Types of constructors
There are three types of
constructors
a) Non-parameterized or Default
Constructor
b)Constructors with default
parameters
c) Parameterized Constructor
d)Copy Constructors
Default constructor:
A constructor that accepts no parameter is
called the default constructor.
With a default constructor, objects are
created just the same way as variables of
other data types are created.
If a class has no explicit constructor
defined, the compiler will supply a default
constructor.
This implicitly declared default constructor
is an inline public member of its class.
When are default constructors
used?
Should be used when you want to
create objects without having to type
the initial objects every time with pre
specified initial values
Should be used if you want to create
array of objects of your class type:
You cant create an array of objects
unless your class has a default
constructor (implicitly or explicitly
defined).
class student{
private:
char name[50];
char gender;
int age;
float marks;
public:
student();
};
student:: student()
{
gets(name,Donald);
sex=M;
age=34;
marks=90;
}
main(){
student s; //default constructor invoked
}
Constructor with default arguments

A constructor can also have default


arguments. A constructor with default
arguments is equivalent to a default
constructor.
Constructor with default
Arguments:-
Example:
item (int x,int y=0); // constructor declaration
item:: item(int x,int y) //constructor definition
{
a=x;
b=y;
}
when we make object of item
item P(11);//11 will be assign to x and 0 to y;
item Q(11,17); //11 will be assign to x and 17 to y;
Parameterized
Constructor:
A constructor that take arguments, is
called as parameterized constructor.
The parameterized constructor allow
us to initialize the various data
elements of different objects with
different values when they are created.
This is achieved by passing different
values as arguments to the constructor
function when the objects are created.
Example:
Rectangle ( float len , float bre )
//Parameterized Constructor.
{
l = len;
b = bre;
}
Parameterized Constructor:
contd..
With a parameterized constructor, the
initial values must be passed at the time of
object created. This can be done in two
manners:
(i)By calling the constructor implicitly
(implicit call) Eg: Rectangle first(8.5,3.9);
(ii)By calling the construct or explicitly
(Explicit call) Eg: Rectangle first =
Rectangle (8.5,3.9);
Temporary Instances(objects):

A temporary instance lives in the memory


as long it is being used or referenced in an
expression and after this it dies.
A temporary instance will not have any
name.
The explicit call to a constructor also
allows you to create a temporary
instance or temporary object.
The temporary instances are deleted when
they are no longer referenced.
Copy Constructor:
A copy constructor is a constructor of
the form classname(classname
&).
A copy constructor takes a reference to an
object of its own class as parameter
So, a constructor having a reference to an
instance of its own class as an argument is
known as copy constructor
Sample (Sample &s) //Copy Constructor
{
i=s.i;
j=s.j;
}
Eg: Sample S2=S1; //Copy constructor
called
Sample S2(S1); //Copy constructor called

In the above code, for the second statement,


the compiler will copy the instance S1 to S2
member by member.
If you have not defined a copy constructor, the
compiler automatically, creates it and it is public.
Copy Constructor is called in
three situations:
1. When an object is passed by value
2. When a function returns an object
3. When you create and initialize with
another object
Constructor Overloading:
When there are two or more
constructors in a class, it is called
constructor overloading.
The constructors are overloaded so
that an object may be initialized,
using:
Different number and different types
of initial values.
Destructor:
A destructor is used to destroy the objects that have
been created by a constructor.
A destructor destroys the values of the object being destroyed.
A destructor is a member function whose name is the
same as the class name but is preceded by tilde(~).
A destructor takes no arguments, and no return types
can be specified for it (not even void).
It is automatically called by the compiler when an object
is destroyed.
A local object, local to a block, is destroyed when the block gets
over; a global or static object is destroyed when the program
terminates.
A destructor cleans up the storage (memory area of the
object) that is no longer accessible.
Need for Destructors:
During construction of any object by
the constructor, resources may be
allocated for use.
These allocated resources must be
deallocated before the object is
destroyed.
A destructor performs these types of
tasks.
Some Characteristics of
Destructors:
1. Destructor functions are invoked automatically when
the objects are destroyed when the scope of the
object gets over.
2. If a class has a destructor, each object of that class
will be de-initialized before the object goes out of
scope.(Local objects at the end of the block defining
them and at the end of the program).
3. Destructor functions also, obey the usual access
rules as other member functions do.
4.No argument can be provided to a destructor, neither
does it return any value.
5. They cannot be inherited nor overloaded.
Invocation
Destructors are called in the reverse order of
invocation of Constructors.

The following restrictions apply


to constructors and destructors:
RESTRICTONS-I
Constructors and destructors do not have return type, not
even void nor can they return values.
References and pointers cannot be used on constructors
and destructors because their addresses cannot be taken.
Constructors cannot be declared with the keyword virtual.
Constructors and destructors cannot be declared static,
const, or volatile.
Unions cannot contain class objects that have constructors
or destructors.
The compiler automatically calls constructors when
defining class objects and calls destructors when class
objects go out of scope.
RESTRICTONS-II
If memory allocation is required for objects, constructors can
explicitly call the new operator.
During cleanup, a destructor may release objects allocated by the
corresponding constructor. To release objects, use the delete
operator.
Derived classes do not inherit constructors or destructors from
their base classes, but they do call the constructor and destructor
of base classes.
Constructors are also called when local or temporary class objects
are created, and destructors are called when local or temporary
objects go out of scope.
We can call member functions from within constructors or
destructors.
Constructor is a member function with the same name as its class.
RESTRICTONS-III
Destructors are usually used to deallocate memory
and do other cleanup for a class object and its
class members when the object is destroyed.
A destructor is called for a class object when that
object passes out of scope or is explicitly deleted.
A destructor is a member function with the same
name as its class prefixed by a ~ (tilde).
If you don't declare a constructor or a destructor,
the compiler makes one for you. The default
constructor and destructor take no arguments and
do nothing.
THE END

Вам также может понравиться