![]() |
VOOZH | about |
In C++, a copy constructor is a constructor that initializes an object as a copy of an existing object of the same class. In this article, we will learn how to declare a copy constructor in a derived class.
We can declare a copy constructor in a derived class by declaring a function with the same name as the derived class, which takes a reference to an object of the derived class as a parameter. Inside the initializer list, call the base class’s copy constructor to ensure that when an object of the derived class is copied, both the base part and the derived part of the object are copied correctly to avoid repeated logic.
DerivedClass(const DerivedClass& otherObj): BaseClass(otherObj)
{
// Derived class copy constructor body
}
Here,
The following program illustrates how we can declare a copy constructor in a derived class in C++.
Original Object: Name: John Id: 100 Id2: 200 Base class copy constructor called. Derived class copy constructor called. Copied Object: Name: John Id: 100 Id2: 200
Time Complexity: O(1)
Auxiliary Space: O(1)