Table of contents
1.
Introduction
2.
Virtual Copy Constructor
2.1.
Example
2.1.1.
Explanation
3.
Frequently Asked Questions
3.1.
Do virtual constructors exist in C++?
3.2.
Why do we need copy constructors?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

Virtual Copy Constructor

Author Yashesvinee V
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Object-Oriented programming introduced the concept of constructors to us. We all know that a constructor is used to initialise all the objects of a class. It is a member function that is called immediately after the creation of an object. Copy constructors initialise an object using another object of the same class. However, this requires the compiler to have the exact type information of the object. To create and initialise an object without having the mentioned data, we use a Virtual Copy Constructor.  

Virtual Copy Constructor

In general, a virtual constructor is used to create and initialise objects when there is no concrete information on the data types associated with the object that is being copied. Unlike copy constructors that initialise objects a compile time, virtual copy constructors perform initialisation during runtime based on some input provided by the user. In other words, a virtual copy constructor offers to clone objects in real-time.

Virtual Copy constructors can be implemented by using two main functions.

  • Create() - This function acts as a virtual constructor. It returns the different types of the base class objects at run-time.
     
  • Clone() - It helps create the clone of an object based on the input it receives.

Example

#include <iostream>
using namespace std;
class shape
{
  public:
  shape() { }
  virtual
  ~shape() { }
  virtual void modifyAttr() = 0;
  static shape *Create(int code);
  virtual shape *Clone() = 0;
};
class square : public shape
{
  public:
  square()
  {
      cout << "Square" << endl;
  }
  void modifyAttr()
  {
      cout<<"The area of square is side*side";
  }
  shape *Clone()
  {
      return new square(*this);
  }
};
class circle : public shape
{
  public:
  circle()
  {
      cout << "Circle" << endl;
  }
  void modifyAttr()
  {
      cout<<"The area of circle is pi*radius*radius";
  }
  shape *Clone()
  {
      return new circle(*this);
  }
};
class rectangle : public shape
{
  public:
  rectangle()
  {
      cout << "Rectangle" << endl;
  }
  void modifyAttr()
  {
      cout<<"The area of rectangle is length*breadth";
  }
  shape*Clone()
  {
      return new rectangle(*this);
  }
};
shape *shape::Create(int code)
{
  if( code == 1 )
  {
      return new square;
  }
  else if( code == 2 )
  {
      return new circle;
  }
  else{
      return new rectangle;
  }
}
class User
{
  public:
  User() : shapes(0)
  {
      int choice;
      cout << "1.Square\t2.Circle\t3.Rectangle\n";
      cout << "Enter the code";
      cin >> choice;
      shapes = shape::Create(choice);
  }
  
  void Action()
  {
      shape *newshape = shapes->Clone();
      newshape->modifyAttr();
      delete newshape;
  }
  private:
  shape *shapes;
};
int main()
{
  User *user = new User();
  user->Action();
  delete user;
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

1.Square 2.Circle 3.Rectangle
Enter the code
3
Rectangle
The area of rectangle is length*breadth

Explanation

As mentioned before, the object type is defined at runtime, not at compile time. It is based on an input provided by the user for a certain condition. The user class creates objects using the Create() function that acts as a virtual constructor. It takes variable choice as input from the user. The Action() function creates duplicates of the object using the Clone() function at run time based on the choice entered by the user and changes the attributes. It may be a call to the Square, Circle or Rectangle class to create objects. The Clone() function performs the function of a virtual copy constructor.

Frequently Asked Questions

Do virtual constructors exist in C++?

Virtual constructors may work only when there is a base class pointer to a derived class object. In C++, a constructor cannot be virtual because, during the execution of the constructor, there is no virtual table in the memory and hence, no virtual pointer. 

Why do we need copy constructors?

The default copy constructor defined by the compiler creates a shallow copy of an object. This means that changes made in the object will be reflected in all its copies. Explicitly defining a copy constructor creates a deep copy of an object where the changes made in the object are not reflected in its copies.

Conclusion

In this article, we have extensively discussed Virtual Copy Constructors in detail. We also learnt how to use the Create() and Clone() functions to implement a virtual copy constructor.

Feeling curious? Coding Ninjas has you covered. Check out our articles on Constructors and DestructorsClasses and Objects in C++ and Virtual Functions. Follow our Guided path for Programming in C++ here.

Explore our Library on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsMachine LearningDeep LearningCloud Computing and many more! If you want to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

Looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc.? Look at the problems, interview experiences, and interview bundle for placement preparations. Upvote our blogs if you find them insightful and engaging! Happy Coding!

Live masterclass