Reputation: 776
I have 4 classes, lets say: class A, class B, class C and class D.
Class B inherits from class A.
Class C and class D inherit from class B.
Classes A and B are abstract classes.
I would like to declare a field in class A, lets say int posision
and define this field in constructors of class C and class D by assigning value of the parameter (int parameterValue
) to this field.
Is there any solution to do this without duplicating line position = parameterValue
in all constructors of descendant classes?
Upvotes: 1
Views: 83
Reputation: 639
Put it in class B and call the super constructor at the begining of the descendent classes. Like that:
class A {
protected:
int position;
};
class B: public A {
public:
B(int parameterValue) : A() {
position = parameterValue;
}
};
class C: public B {
public:
C(int parameterValue) : B(parameterValue) {
}
};
Upvotes: 2