Search code examples
c++inheritanceconstructorarduinoderived-class

dynamic base class constructor call in derived class constructor in c++


I have a base class in a library which I don't want to modify for compatibility reasons. This class stores certain settings that cannot be modified after construction; the correct arguments must be provided at the time of construction.

My own code contains a class that is derived from that class. The argument structure of the constructor of the the derived class is different from the constructor of the base class; arguments are not simply passed through to the base class constructor.

There are three predetermined sets of arguments that will be used to construct the base class from the derived class. The decision as to which of these three to use is based upon the arguments to the derived class constructor. Since the base class arguments are needed in the member initializer list, this decision needs to be made before entering the derived constructor's body.

What is the most elegant in this case of accomplishing this with code that need to be compiled for an Arduino (Mega)?

Pseudo-code demonstrating the setup:

class base{
    base(type1 arg1, type2 arg2){/*do something*/}
};

class derived : base{
    int variable;
    derived(typeA a, typeB b, int c) :
    // if a,b match first scenario:
    base(1, 2) 
    // if a,b match second scenario:
    base(3, 4) 
    // if a,b match third scenario:
    base(1, 4) 
    {
        variable = c;
    }
};

Solution

  • This is a case where a helper function to build derived instances would probably work better for you.

    class derived : base{
        int variable;
        derived(char a, char b, int c) : base(a, b), variable(c) { }
    
    public:
        static derived build(int a, int b, int c) {
            if(/* a,b match first scenario */) {
                return dervied("w", "x", c);
            }
            else if(/* a,b match second scenario */) {
                return dervied("x", "y", c);
            }
            else if(/* a,b match third scenario */) {
                return dervied("1", "2", c);
            }
            else {
                throw std::runtime_error("Bad arguments");
            }
        }
    };
    

    This lets you analyze any arguments before constructing your derived, and by extension your base.