C++ Virtual Constructor

In C++ and other object-oriented programming languages, a virtual constructor is a mechanism of having a base class pointer to a derived class object.

What is a Virtual Constructor/Destructor?

Virtual Constructor

A constructor is a member feature of a class that has the same name as the class name. It enables initializing the object of a class. It can either receive the arguments or not. It is used to allocate memory to an object of the class. It is called every time an instance of the class is created. It can be defined with arguments or without arguments. There may be many constructors in a class. It may be overloaded; however, it can’t be inherited or virtual. There is an idea of a copy constructor used to initialize an object from any other object.

More like this:

Virtual Destructor

Like a constructor, a destructor is also a member feature of a class. It preceded through a tilde ~ operator. It enables to deallocate the memory of an object. It is called when an object of the class is deleted or freed. There’s usually a single destructor without any parameters in a class, so it can’t be overloaded. It is called in the reverse order of the Constructor. If a class is inherited through another class and both the classes have a destructor, then it is called first, observed by the destructor of the base class.

Why C++ does not have a Virtual Constructor?

  • The virtual mechanism works when we have a base class pointer to a derived class object.
  • In C++, the Constructor can’t be virtual because when a class’s Constructor is performed, there’s no virtual table withinside the memory, which means no virtual Pointer defined yet. So, the Constructor must be non-virtual.
  • But virtual destructor is possible.

Example

class b {
  public:
    b() {
      cout << "Constructing base\ n";
    }
  virtual~b() {
    cout << "Destructing base\ n";
  }
};
class d: public b {
  public: d() {
    cout << "Constructing derived\ n";
  }
  virtual~b() {
    cout << "Destructing derived\ n";
  }
};
int main(void) {
  d * derived = new d();
  b * bptr = derived;
  delete bptr;
  return 0;
}

Output

Constructing base
Destructing base
Constructing derived
Destructing derived

How are constructors different from a normal function?

A constructor is different from a normal member function in the following ways:

  • Constructors do not have a return type
  • A constructor is automatically referred to as when an object is created.
  • If we will not specify a constructor, the C++ compiler generates a default Constructors for.

Types of Constructors

1- Default Constructors: It is the Constructor which does not take any argument nor parameters.

Example of default constructor

class cube {
  Public:
    int side;
  cube() {
    side = 5;
  }
};
int main() {
  cube c;
  cout << c.side;
}

Output

5

2- Parameterized Constructor: a contractor that takes parameters when it’s initialized. Typically, those arguments help initialize an object when it’s created. To create a parameterized constructor, add parameters to it the way you would to another function. When you define the Constructor’s body, you have to use the parameters to initialize the object.

Example

class cube {
  public:
    int side;
  cube(int x) {
    Side = x;
  }
};

int main() {
  cube c1(A);
  cube c2(B);
  cube c3(C);
  cout << c1.side;
  cout << c2.side;
  cout << c3.side;
}

Output

A
B
C

By using parameterized Constructor in the above example, we have initialized 3 objects with defined values.

3- Copy Constructor: A copy constructor is a member characteristic that initializes an object using another object of the same class.

Using a virtual copy constructor, the programmer might be able to create an object without knowing the data type of the object.

In the C++ programming language, a copy Constructor is used to develop an object copied from another. Still, if you need the program to decide at the runtime about the type of object created, i.e., that object type is described at runtime, not at compile-time, and is based on some input provided through the user for a certain condition. In this situation, we want a copy constructor with some special powers to do that thing. So to do that virtual copy constructor is declared that gives the cloning of objects in real-time.

When we define one or more non-default constructors for a class, a default constructor must be defined as the compiler will not define a default constructor. However, it isn’t important, but it is considered the best practice to define a default constructor.

What Is Pure Virtual Function?

A pure virtual function is a function this is required to be implemented through a derived class. Classes containing virtual techniques are termed “abstract”, and they can’t be instantiated. A subclass of abstract class can only be instantiated if all inherited pure virtual techniques have been applied through that class or a parent class. Pure virtual techniques have a declaration and no definition.

Although pure virtual techniques usually don’t have any implementation in the class that declares them, pure virtual techniques in some languages are permitted to include an implementation in their declaring class, offering default behavior or fallback that a derived class can delegate to, if appropriate.

A pure virtual function can be used where the technique declarations are getting used to define an interface – similar to what that interface keyword in Java specifies. Derived classes will supply implementations. The abstract class will serve as an interface, which includes pure virtual functions but no ordinary methods or data members. In C++, the use of such purely abstract classes as interfaces works because C++ supports multiple inheritances. However, because many OOP languages do not support multiple inheritances, they often provide a separate interface mechanism.

Example

# include < iostream >
  using namespace std;
class B {
  public:
    virtual void s() = 0; // Pure Virtual Function 
};
class D: public B {
  public: void s() {
    cout << "Virtual Function in Derived class/n";
  }
};
int main() {
  B * b;
  D dobj;
  b = & dobj:
    b -> s();
}

Output

Virtual Function in Derived class

Do constructors always have to be public?

  • No, Constructors can be public, protected, private, or default.
  • Making something private does not mean nobody can access it. It simply means that nobody outside the class can access it. So private Constructor is beneficial too.
  • The use of private Constructor is to provide singleton classes. A singleton class limits the number of objects created to one. Using a private constructor, we can ensure that no multiple objects can be created at a time.
  • Languages differ in their behavior while the constructor or destructor of an object is running. For this reason, calling virtual features in constructors is generally discouraged.

Leave a Reply

Your email address will not be published. Required fields are marked *