Search code examples
c++abstract-class

Abstract variable to be initialized on constructor


I have a class (let's call it Example) that has itself a variable child. This variable is an object of either class Child1 or Child2 which are both childs of an abstract class Father. I would like for this to be defined on the constructor. This is what I try:

class Example {
public:
    Father child;  //This does not work because father is abstract
};

Example::Example(bool use_1) {
    if use_1 { child = Child1(); }
    else { child = Child2(); }
}

I currently define both objects on public and init only one but it seems quite ugly.

class Example {
public:
    Child1 child1;
    Child2 child2;
    //father child;  This does not work because father is abstract
};

Example::Example(bool use_1) {
    if use_1 { 
        child1 = Child1(); // I would like to use child only here...
    }
    else { 
        child2 = Child2(); // ... and here
    }
}

Is there a better way to do this?


Solution

  • Assuming your Child1 and Child2 are derived from Father, this is a standard case for dynamic polymorphism. You need to hold a pointer (usually a smart pointer) instead of the object itself:

    class Example {
    public:
        std::unique_ptr<Father> child;
    };
    
    Example::Example(bool use_1) {
        if( use_1 ) { child = std::make_unique<Child1>(); }
        else { child = std::make_unique<Child2>(); }
    }