Search code examples
c++inheritancesuperclassinitialization-list

How can i initialize superclass params from within the child c-tor in C++?


Watch the following example:

class A {
public:
    A(int param1, int param2, int param3) {
        // ...
    }
};

class B : public A {
public:
    B() : m_param1(1), m_param(2), m_param(3), A(m_param1, m_param2, m_param3) {
        // ...
    }
};

B b;

Obviously, when "b" will be created, A's ctor will be called before the parameters of B will be initialized.

This rule prevents me from creating "wrapper" classes which simplify the class's initialization.

What is the "right way" for doing it?

Thanks, Amir

PS: In my particular case, the parameters are not primitives, this example just helped me to explain myself.


Solution

  • "The parameters are not primitives". So you have something like this?

    class Param { /*...*/ };
    class A {
    public:
      A(const Param& param1, const Param& param2, const Param& param3);
    };
    
    class B : public A {
    public:
      B();
    private:
      Param m_param1;
      Param m_param2;
      Param m_param3;
    };
    

    And you want to pass the members of B to the constructor of A. How about this?

    class B_params {
    protected:
      B_params(int v1, int v2, int v3);
      Param m_param1;
      Param m_param2;
      Param m_param3;
    };
    class B : private B_params, public A {
    public:
      B();
    };
    
    B_params::B_params(int v1, int v2, int v3)
      : m_param1(v1), m_param2(v2), m_param3(v3) {}
    B::B() : B_params(1,2,3), A(m_param1, m_param2, m_param3) {}
    

    Just make sure B_params comes before A in the list of B's inherited classes.