The Wayback Machine - https://web.archive.org/web/20240828110659/https://www.geeksforgeeks.org/advanced-c-virtual-constructor/
Open In App

Advanced C++ | Virtual Constructor

Last Updated : 17 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Can we make a class constructor virtual in C++ to create polymorphic objects? No. C++ being a statically typed (the purpose of RTTI is different) language, it is meaningless to the C++ compiler to create an object polymorphically. The compiler must be aware of the class type to create the object. In other words, what type of object to be created is a compile-time decision from the C++ compiler perspective. If we make a constructor virtual, the compiler flags an error. In fact, except inline, no other keyword is allowed in the declaration of the constructor. 

In practical scenarios, we would need to create a derived class object in a class hierarchy based on some input. In other words, object creation and object type are tightly coupled which forces modifications to extended. The objective of the virtual constructor is to decouple object creation from its type. 

How can we create the required type of an object at runtime? For example, see the following sample program: 

C++
#include <iostream>
using namespace std;

//// LIBRARY START
class Base
{
public:

    Base() { }

    virtual // Ensures to invoke actual object destructor
    ~Base() { }

    // An interface
    virtual void DisplayAction() = 0;
};

class Derived1 : public Base
{
public:
    Derived1()
    {
        cout << "Derived1 created" << endl;
    }

    ~Derived1()
    {
        cout << "Derived1 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived1" << endl;
    }
};

class Derived2 : public Base
{
public:
    Derived2()
    {
        cout << "Derived2 created" << endl;
    }

    ~Derived2()
    {
        cout << "Derived2 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived2" << endl;
    }
};

//// LIBRARY END

class User
{
public:

    // Creates Drived1
    User() : pBase(nullptr)
    {
        // What if Derived2 is required? - Add an if-else ladder (see next sample)
        pBase = new Derived1();
    }

    ~User()
    {
        if( pBase )
        {
            delete pBase;
            pBase = nullptr;
        }
    }

    // Delegates to actual object
    void Action()
    {
        pBase->DisplayAction();
    }

private:
    Base *pBase;
};

int main()
{
    User *user = new User();

    // Need Derived1 functionality only
    user->Action();

    delete user;
}

In the above sample, assume that the hierarchies Base, Derived1 and Derived2 are part of library code. The class User is an utility class trying to make use of the hierarchy. The main function is consuming Base hierarchy functionality via the User class. 

The User class constructor is creating Derived1 object, always. If the User‘s consumer (the main in our case) needs Derived2 functionality, the User needs to create “new Derived2()“, which forces recompilation. Recompiling is a bad way of design, so we can opt for the following approach. 

Before going into the details, let us answer the question, who will dictate to create either of Derived1 or Derived2 object? Clearly, it is the consumer of the User class. The User class can make use of an if-else ladder to create either Derived1 or Derived2, as shown in the following sample: 

C++
#include <iostream>
using namespace std;

//// LIBRARY START
class Base
{
public:
    Base() { }

    virtual // Ensures to invoke actual object destructor
    ~Base() { }

    // An interface
    virtual void DisplayAction() = 0;
};

class Derived1 : public Base
{
public:
    Derived1()
    {
        cout << "Derived1 created" << endl;
    }

    ~Derived1()
    {
        cout << "Derived1 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived1" << endl;
    }
};

class Derived2 : public Base
{
public:
    Derived2()
    {
        cout << "Derived2 created" << endl;
    }

    ~Derived2()
    {
        cout << "Derived2 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived2" << endl;
    }
};

//// LIBRARY END

class User
{
public:

    // Creates Derived1 or Derived2 based on input
    User() : pBase(nullptr)
    {
        int input; // ID to distinguish between
                // Derived1 and Derived2

        cout << "Enter ID (1 or 2): ";
        cin >> input;

        while( (input != 1) && (input != 2) )
        {
            cout << "Enter ID (1 or 2 only): ";
            cin >> input;
        }

        if( input == 1 )
        {
            pBase = new Derived1;
        }
        else
        {
            pBase = new Derived2;
        }

        // What if Derived3 being added to the class hierarchy?
    }

    ~User()
    {
        if( pBase )
        {
            delete pBase;
            pBase = nullptr;
        }
    }

    // Delegates to actual object
    void Action()
    {
        pBase->DisplayAction();
    }

private:
    Base *pBase;
};

int main()
{
    User *user = new User();

    // Need either Derived1 or Derived2 functionality
    user->Action();

    delete user;
}

The above code is *not* open for extension; an inflexible design. In simple words, if the library updates the Base class hierarchy with new class Derived3, how can the User class create Derived3 object? One way is to update the if-else ladder that creates Derived3 object based on new input ID 3 as shown below: 

C++
#include <iostream>
using namespace std;

class User
{
public:
    User() : pBase(nullptr)
    {
        // Creates Drived1 or Derived2 based on need

        int input; // ID to distinguish between
                // Derived1 and Derived2

        cout << "Enter ID (1 or 2): ";
        cin >> input;

        while( (input != 1) && (input != 2) )
        {
            cout << "Enter ID (1 or 2 only): ";
            cin >> input;
        }

        if( input == 1 )
        {
            pBase = new Derived1;
        }
        else if( input == 2 )
        {
            pBase = new Derived2;
        }
        else
        {
            pBase = new Derived3;
        }
    }

    ~User()
    {
        if( pBase )
        {
            delete pBase;
            pBase = nullptr;
        }
    }

    // Delegates to actual object
    void Action()
    {
        pBase->DisplayAction();
    }

private:
    Base *pBase;
};

The above modification forces the users of the User class to recompile; again, bad (inflexible) design! Also, it won’t close the User class from further modifications due to Base extension. 

The problem is with the creation of objects. Addition of new class to the hierarchy is forcing the dependents of the User class to recompile. Can’t we delegate the action of creating objects to class hierarchy itself or to a function that behaves virtually? By delegating the object creation to class hierarchy (or to a static function), we can avoid the tight coupling between the User and Base hierarchy. Enough theory; see the following code: 

C++
#include <iostream>
using namespace std;

//// LIBRARY START
class Base
{
public:

    // The "Virtual Constructor"
    static Base *Create(int id);

    Base() { }

    virtual // Ensures to invoke actual object destructor
    ~Base() { }

    // An interface
    virtual void DisplayAction() = 0;
};

class Derived1 : public Base
{
public:
    Derived1()
    {
        cout << "Derived1 created" << endl;
    }

    ~Derived1()
    {
        cout << "Derived1 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived1" << endl;
    }
};

class Derived2 : public Base
{
public:
    Derived2()
    {
        cout << "Derived2 created" << endl;
    }

    ~Derived2()
    {
        cout << "Derived2 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived2" << endl;
    }
};

class Derived3 : public Base
{
public:
    Derived3()
    {
        cout << "Derived3 created" << endl;
    }

    ~Derived3()
    {
        cout << "Derived3 destroyed" << endl;
    }

    void DisplayAction()
    {
        cout << "Action from Derived3" << endl;
    }
};

// We can also declare "Create" outside Base
// But it is more relevant to limit it's scope to Base
Base *Base::Create(int id)
{
    // Just expand the if-else ladder, if new Derived class is created
    // User code need not be recompiled to create newly added class objects

    if( id == 1 )
    {
        return new Derived1;
    }
    else if( id == 2 )
    {
        return new Derived2;
    }
    else
    {
        return new Derived3;
    }
}
//// LIBRARY END

//// UTILITY START
class User
{
public:
    User() : pBase(nullptr)
    {
        // Receives an object of Base hierarchy at runtime

        int input;

        cout << "Enter ID (1, 2 or 3): ";
        cin >> input;

        while( (input != 1) && (input != 2) && (input != 3) )
        {
            cout << "Enter ID (1, 2 or 3 only): ";
            cin >> input;
        }

        // Get object from the "Virtual Constructor"
        pBase = Base::Create(input);
    }

    ~User()
    {
        if( pBase )
        {
            delete pBase;
            pBase = nullptr;
        }
    }

    // Delegates to actual object
    void Action()
    {
        pBase->DisplayAction();
    }

private:
    Base *pBase;
};

//// UTILITY END

//// Consumer of User (UTILITY) class
int main()
{
    User *user = new User();

    // Action required on any of Derived objects
    user->Action();

    delete user;
}

The User class is independent of object creation. It delegates that responsibility to Base, and provides an input in the form of ID. If the library adds new class Derived4, the library modifier will extend the if-else ladder inside Create to return proper object. The consumers of User need not recompile their code due to extension of Base. 

Note that the function Create is used to return different types of Base class objects at runtime. It acts like a virtual constructor, also referred to as Factory Method in pattern terminology. 

The pattern world demonstrates different ways to implement the above concept. Also, there are some potential design issues with the above code. Our objective is to provide some insights into virtual construction, i.e., creating objects dynamically based on some input.



Previous Article
Next Article

Similar Reads

Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Calling virtual methods in constructor/destructor in C++
Prerequisite: Virtual Function in C++Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. You can call a virtual
2 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &amp;lt;iostream&amp;gt; using namespace std; class Base { public: void print() { cout &amp;lt;&amp;lt; &amp;quot;Base class print function \n&amp;quot;; } void invoke() { cout &amp;lt;&amp;lt; &amp;quot;Base class invoke function \n&amp;quot;;
2 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we initialize our own, the compiler by default creates a default constructor for every class; But, if we define our own constructor, the compiler doesn't create the default constructor. This is so because the default constructor does not take any argument and if two default constructors
1 min read
What is conversion constructor in C++?
Pre-requisite: Type Conversion in C++ and Use of explicit keyword in C++ A conversion constructor is a single-parameter constructor that is declared without the function specifier explicitly. The compiler uses conversion constructors to convert objects from the type of the first parameter to the type of the conversion constructor's class. Example:
3 min read
Passing a vector to constructor in C++
When class member is a vector object (not a reference).We can simply assign in constructor. C/C++ Code // Passing vector object to a constructor. #include &amp;lt;iostream&amp;gt; #include &amp;lt;vector&amp;gt; using namespace std; class MyClass { vector&amp;lt;int&amp;gt; vec; public: MyClass(vector&amp;lt;int&amp;gt; v) { vec = v; } void print()
2 min read
Constructor Delegation in C++
Sometimes it is useful for a constructor to be able to call another constructor of the same class. This feature, called Constructor Delegation, was introduced in C++ 11.An example program without delegation : C/C++ Code // A C++ program to demonstrate need of // constructor delegation. #include &lt;iostream&gt; using namespace std; class A { int x,
3 min read
Is body of a Default Constructor blank in C++?
The answer to this question depends upon 2 scenarios: Scenario 1: When there is a Virtual function in the program: In this scenario, compiler automatically creates virtual table(known as V-Table) and VVPTR(Virtual Void Pointer). V-Table contains the virtual method calls whereas VVPTR contain the address of virtual methods which are present in V-Tab
2 min read
How to create a List with Constructor in C++ STL
Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list. A list can be created with the he
2 min read
Dynamic Constructor in C++ with Examples
When allocation of memory is done dynamically using dynamic memory allocator new in a constructor, it is known as dynamic constructor. By using this, we can dynamically initialize the objects. Example 1: C/C++ Code #include &lt;iostream&gt; using namespace std; class geeks { const char* p; public: // default constructor geeks() { // allocating memo
3 min read
Difference Between Constructor and Destructor in C++
Constructor: A constructor is a member function of a class that has the same name as the class name. It helps to initialize the object of a class. It can either accept the arguments or not. It is used to allocate the memory to an object of the class. It is called whenever an instance of the class is created. It can be defined manually with argument
3 min read
Constructor in Multilevel Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multilevel Inheritance Derivation of a class from another derived class is called Multilevel Inheritance. Class A is the base class for the d
2 min read
Constructor in Multiple Inheritance in C++
Constructor is a class member function with the same name as the class. The main job of the constructor is to allocate memory for class objects. Constructor is automatically called when the object is created. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can derive from several(two or more) base classes. The construct
2 min read
How to Define the Constructor Outside the Class in C++?
A constructor is a special type of member function whose task is to initialize the objects of its class. It has no return type so can't use the return keyword and it is implicitly invoked when the object is created. Constructor is also used to solve the problem of initialization. It is called after the object is created.Same name as of class. Const
2 min read
C++ default constructor | Built-in types for int(), float, double()
A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.It will be called by the compiler when in need(precisely
2 min read
Is it possible to call constructor and destructor explicitly in C++?
A constructor is a special member function that is automatically called by the compiler when an object is created and the destructor is also a special member function that is also implicitly called by the compiler when the object goes out of scope. They are also called when a dynamically allocated object is allocated and destroyed, a new operator a
3 min read
Order of Constructor/ Destructor Call in C++
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that t
4 min read
Can a constructor be private in C++ ?
Prerequisite : Constructors A constructor is a special member function of a class which initializes objects of a class. In C++, constructor is automatically called when object of a class is created. By default, constructors are defined in public section of class. So, question is can a constructor be defined in private section of class ? Answer : Ye
3 min read
When is a Copy Constructor Called in C++?
A copy constructor is a member function that initializes an object using another object of the same class. The Copy constructor is called mainly when a new object is created from an existing object, as a copy of the existing object. In C++, a Copy Constructor may be called for the following cases: 1) When an object of the class is returned by value
2 min read
Parameterized Constructor in C++
In C++, parameterized constructor is a type of constructor that can accept arguments. Parameterized Constructors make it possible to pass arguments to initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the pa
4 min read
When Should We Write Our Own Copy Constructor in C++?
A copy constructor is a member function that initializes an object using another object of the same class. (See this article for reference). When should we write our own copy constructor?C++ compiler provides a default copy constructor (and assignment operator) with class. When we don't provide an implementation of the copy constructor (and assignm
2 min read
Copy Constructor in C++
A copy constructor is a type of constructor that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.   The process of initializing members of an object through a copy
7 min read
Why copy constructor argument should be const in C++?
When we create our own copy constructor, we pass an object by reference and we generally pass it as a const reference. One reason for passing const reference is, we should use const in C++ wherever possible so that objects are not accidentally modified. This is one good reason for passing reference as const, but there is more to it. For example, pr
3 min read
Copy Constructor vs Assignment Operator in C++
Copy constructor and Assignment operator are similar as they are both used to initialize one object using another object. But, there are some basic differences between them: Copy constructor Assignment operator It is called when a new object is created from an existing object, as a copy of the existing objectThis operator is called when an already
2 min read
C | Advanced Pointer | Question 1
C/C++ Code void fun(int *p) { int q = 10; p = &q; } int main() { int r = 20; int *p = &r; fun(p); printf(\"%d\", *p); return 0; } (A) 10 (B) 20 (C) Compiler error (D) Runtime Error Answer: (B)Explanation: Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains uneffected. If we want to change a local poi
2 min read
C | Advanced Pointer | Question 2
Assume sizeof an integer and a pointer is 4 byte. Output? #include &lt;stdio.h&gt; #define R 10 #define C 20 int main() { int (*p)[R][C]; printf(&quot;%d&quot;, sizeof(*p)); getchar(); return 0; } (A) 200 (B) 4 (C) 800 (D) 80 Answer: (C) Explanation: Output is 10*20*sizeof(int) which is “800â€ģ for compilers with integer size as 4 bytes. When a point
1 min read
C | Advanced Pointer | Question 3
#include &lt;stdio.h&gt; int main() { int a[5] = {1,2,3,4,5}; int *ptr = (int*)(&amp;a+1); printf(&quot;%d %d&quot;, *(a+1), *(ptr-1)); return 0; } (A) 2 5 (B) Garbage Value (C) Compiler Error (D) Segmentation Fault Answer: (A) Explanation: The program prints “2 5â€ģ. Since compilers convert array operations in pointers before accessing the array ele
1 min read
C | Advanced Pointer | Question 4
#include &lt;stdio.h&gt; char *c[] = {&quot;GeksQuiz&quot;, &quot;MCQ&quot;, &quot;TEST&quot;, &quot;QUIZ&quot;}; char **cp[] = {c+3, c+2, c+1, c}; char ***cpp = cp; int main() { printf(&quot;%s &quot;, **++cpp); printf(&quot;%s &quot;, *--*++cpp+3); printf(&quot;%s &quot;, *cpp[-2]+3); printf(&quot;%s &quot;, cpp[-1][-1]+1); return 0; } (A) TEST s
1 min read
C | Advanced Pointer | Question 5
Predict the output #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void fun(char** str_ref) { str_ref++; } int main() { char *str = (void *)malloc(100*sizeof(char)); strcpy(str, &quot;GeeksQuiz&quot;); fun(&amp;str); puts(str); free(str); return 0; } (A) GeeksQuiz (B) eeksQuiz (C) Garbage Value (D) Compiler Error Answer
1 min read
Article Tags :
Practice Tags :