SigGP
SigGP

Reputation: 776

Inheritance without duplicating code

I have 4 classes, lets say: class A, class B, class C and class D.

  1. Class B inherits from class A.

  2. Class C and class D inherit from class B.

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

Answers (2)

Kokozaurus
Kokozaurus

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

Jarod42
Jarod42

Reputation: 217075

You might use inherited constructor:

struct A
{
    A(int position) : position(position) {}
    virtual ~A() = default;

    int position;
};

struct B : public A
{
    using A::A;
};

struct C : public B
{
    using B::B;
};

struct D : public B
{
    using B::B;
};

Demo

Upvotes: 4

Related Questions