0% found this document useful (0 votes)
3 views

Copy Constructor

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Copy Constructor

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Constructor and Destructor

11 July 2024 18:25

Constructor:
1. Constructor are special member functions which allocate memory space for newly created object
2. Beside this the constructor can initialize the member variables of the object
3. Constructor is called automatically by complier at the time creation of some object
4. We can not call constructor explicitly
5. The name of the constructor is same as that of the class
6. By default return type of the constructor is void

Types:
1. System default Constructor:
That can create object but does not assign any values to its attributes is called " System default Constructor"
Can only allocate memory space for newly created object but it can not perform initilialization operation
It is supplied by the complier itself if no user defined constructor is supplied
It can not accept any parameters and arguments

2. User defined Constructor


2.1 No Argument constructors (Default constructors)
2.2 Parameterized Constructors

3. Copy Constructor:
It allows us to create an object as an exact copy of some existing object in terms of its attributes

Point(Point obj) // Copy Constructor


{
x=obj.x;
y=obj.y;
}

Point(Point & obj) // Copy Constructor


{
x=obj.x;
y=obj.y;
}

Why do we need reference to pass in Copy Constructor?

Ans: if we pass an object in a function using call by value method


Copy constructor will be invoked to create the formal object (that is the object in the formal parameter)

Now if we pass the object of the copy constructor has the call by value method then again copy constructor will be called for that object

New Section 1 Page 1


Now if we pass the object of the copy constructor has the call by value method then again copy constructor will be called for that object
Resulting in a recursive call of copy constructor which will have no termination,
So we need to pass the object in the copy constructor as call by reference

Destructor:
Its is a special member function which deallocate memory space allocated to an object by the constructor
Name of the destructor is same as that of the class with ~ (tilda) character prior to it
By default the return type of the destructor is void
Destructor can not take any parameters

If we create object using pointer

Two types of Destructor


1. User
2. Default

Point(Point obj) // Copy Constructor


{
x=obj.x;
y=obj.y;
}

Point(Point & obj) // Copy Constructor


{
x=obj.x;
y=obj.y;
}

New Section 1 Page 2


New Section 1 Page 3

You might also like