Let’s learn more about the types of constructors in C++.
Copy Constructor
The copy constructor is a constructor which creates an object by initializing it with an object of the same class, which has been created previously. The copy constructor is used to :
- Initialize one object from another of the same type.
- Copy an object to pass it as an argument to a function.
- Copy an object to return it from a function.
The compiler itself defines a copy constructor if it is not defined in a class. If the class has pointer variables and has some dynamic memory allocations, you must use a copy constructor.
A copy constructor has the following general function prototype:
ClassName (const ClassName &old_obj);
Example:
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1;
}
// Copy constructor
Point(const Point &p1) { x = p1.x; y = p1.y; }
intgetX() { returnx; }
intgetY() { returny; }
};
intmain()
{
Point p1(10, 15); // Default constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = "<< p1.getX() << ", p1.y = "<< p1.getY();
cout << "\n p2.x = "<< p2.getX() << ", p2.y = "<< p2.getY();
return0;
}
Output:
p1.x = 10, p1.y = 15 p2.x = 10, p2.y = 15
If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between objects. In general the compiler created copy constructor works fine. But in user defined copy constructor, we can make sure that pointers (or references) of copied object point to new memory locations, in addition.

Dynamic Constructor
Constructors allocate a dynamically created memory to the object. Thus object uses the dynamically created memory region. So when you use dynamic memory allocator new inside the constructor to create dynamic memory, it is called dynamic constructor.
Points To Remember:
1. The dynamic constructor does not create the memory of the object but it creates the memory block that is accessed by the object.
2. You can also gives arguments in the dynamic constructor you want to.
Example:
#include <iostream> using namespace std; class news { const char* s; public: // default constructor news() { // allocating memory at run time s = new char[5]; s = "news"; } void display() { cout << s << endl; } }; int main() { news obj = new news(); obj.display();} |
Output:
news