Reputation: 35982
class A // abstract class
{
protected:
int m_iA;
int m_iB;
int m_iC;
int m_iD;
int m_iE
~A();
};
class B : public A // abstract class
{
protected:
double m_dA;
double m_dB;
double m_dC;
double m_dD;
~B();
};
class C : public B
{
public:
C(int iA, int iB, int iC, int iD, int iE, double dA, double dB, double dC, double dD)
{
}
}
Question> As you can see above example, both base class A
and B
contain many member variables. What is the better solution to pass those initial values from class C
up to the base classes?
Method1> Assign the base class member variables directly inside the constructor body of class C
.
Method2> Pass all initial values from constructor of C
to B
, and then finally to A
.
Thank you
Upvotes: 0
Views: 110
Reputation: 34636
Using C++11, you can get away with a bit less overhead than you expected:
class A { // abstract class
protected:
int m_iA;
int m_iB;
int m_iC;
int m_iD;
int m_iE
A(int iA, int iB, int iC, int iD, int iE)
: m_iA(iA), m_iB(iB), m_iC(iC), m_iD(iD), m_iE(iE) {}
~A();
};
class B : public A { // abstract class
protected:
double m_dA;
double m_dB;
double m_dC;
double m_dD;
B(int iA, int iB, int iC, int iD, int iE, double dA, double dB, double dC, double dD)
: A(iA,iB,iC,iD,iE), m_dA(dA), m_dB(dB), m_dC(dC), m_dD(dD) {}
~B();
};
class C : public B {
public:
using B::B;
}
Upvotes: 2
Reputation: 514
Having such a long constructor in the first place is... not preferable, but regardless: Either way works equally well, I would say it is a matter of personal choice.
Upvotes: 0
Reputation: 146970
The better idea is to take a tuple
, array
or custom struct which contains the initialization values, and then unpack it in the constructor for B and A. Then C's constructor only needs to take two objects.
Upvotes: 1
Reputation: 2491
I would recommend making constructors for A and B, and have them take the initialization values, and apply them. Then C calls B's constructor, passing values to it, and so on. This way if there is ever another class inheriting from B or A, it follows the same pattern, and this can be enforced, by only having constructors that require initialization values.
Upvotes: 5
Reputation: 308364
Create constructors for the base classes that take initialization values, and use them in C
's constructor initialization list.
Upvotes: 2