How can i initialize superclass params from within

2019-05-23 04:43发布

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.

3条回答
forever°为你锁心
2楼-- · 2019-05-23 04:48

"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.

查看更多
放我归山
3楼-- · 2019-05-23 04:57

Just call A's constructor:

class B : public A
{
public:
    B() : A(1 ,2, 3)
    {
    }; // eo ctor
}; // eo class B

EDIT:

Just read your comment to your original post. It's important to be clear about these things :) Anyway, this answer still holds true if you want to create new data in B, track it in B, and pass it to A:

class Object
{
private:
    int i;
public:
    Object(int _i) : i(_i){};
};

class A
{
public:
    A(Object* _1, Object* _2, Object* _3)
    {
    };
};

class B : public A
{
private:
    Object* _1;
    Object* _2;
    Object* _3;

public:
    B() : A(_1 = new Object(1), _2 = new Object(2), _3 = new Object(3))
    {
    };
};
查看更多
Rolldiameter
4楼-- · 2019-05-23 05:01

Not sure I'm getting your question.

If you just want something that helps you to initialize A with some given parameters, you should use an A constructor with default values:

class A {
public:
    A(int param1 = 1, int param2 = 2, int param3 =3) {
        // ...
    }
};
查看更多
登录 后发表回答