Unit 2 (Topic 2)
Unit 2 (Topic 2)
Unit – 2 (Topic – 2)
Constructors & Destructors
Prepared By
Prof. Shah Brijesh
Constructors
Constructors:
-> A constructor is a “special” member function whose task is to initialize the
objects of its class.
-> It is special because its name is the same as the class name.
-> The constructor is invoked whenever an object of its associated class is created.
-> It is called constructor because it constructs the values of data members of the
class.
-> Characteristics of Constructor
1. They should be declared in the public section
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void and therefore, they cannot return
values.
4. They cannot be inherited, through a derived class can call the base class
constructor.
5. Like other C++ functions, they can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to their addresses.
8. An object with a constructor cannot be used as a member of a union.
9. They make ‘implicit calls’ to the operators new and delete when memory
allocation is required.
Constructors
Constructors:
For Example:
class A
{
int m, n;
public:
A() // Constructor
{
m=0;
n = 0; }
void disp()
{
cout<<“\n m=“<<m;
cout<<“\n n=“<<n; }
};
void main()
{
A x; // Create an object x and call the Constructor function.
x.disp();
}
Constructors
Types Of Constructors:
-> Following are the types of the constructor
1. Default Constructor
2. Parameterized Constructor
3. Multiple Constructors / Constructor Overloading
4. Dynamic Constructor
5. Copy Constructor
1. Default Constructor:
-> A constructor without any argument is called Default Constructor.
-> When we create default constructor, it is guaranteed that an
object created by the class will be initialized automatically.
-> For Example:
A x;
-> not only creates the object x of the type A but also initialize its
data member m and n to zero.
-> There is no need to write any statement to invoke the
constructor functions.
Constructors
Types Of Constructors:
2. Parameterized Constructor:
-> The constructor A(), defined above, initializes the data members of all
the objects to zero.
-> However, in practice it may be necessary to initialize the various data
elements of different objects with different values when they are created.
-> C++ permits us to achieve this objective by passing arguments to the
constructor function when the objects are created.
-> The constructors that can take arguments are called parameterized
constructors.
-> The constructor A() may be modified to take arguments as shown below
class A
{ int m, n;
public:
A(int x, int y) {
m=x;
n=y; }
………………..
};
Constructors
Types Of Constructors:
2. Parameterized Constructor:
-> When the constructor has been parameterized, the object declaration
statement such as
A x;
-> may not work.
-> We must pass the initial values as arguments to the constructor function when
an object is declared.