Virtual Constructors

It’s not possible to define virtual constructors. But it’s possible to define a virtual function that calls a constructor. An useful application of this is defining a clone operation.

#include <iostream>

struct A {
    A() {
        std::cout << "A constructor\n"; 
    };
    virtual A* new_A(){ return new A(); };
};
struct B:A {
    B() {
        std::cout << "B constructor\n"; 
    };
    virtual A* new_A(){ return new B(); };
};

void func(A *obj1, A *obj2){
    A* obj3 = obj1->new_A(); // A
    A* obj4 = obj2->new_A(); // A, B
}

int main (){

    A obj1; //A 
    B obj2; //A, B
    
    func(&obj1, &obj2);

    return 0;
}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s