Warm tip: This article is reproduced from stackoverflow.com, please click
c++ inheritance

best practice for C++ inheritance

发布于 2020-03-27 15:45:26

If I want to use inheritance to avoid repeating the common_method method below

int A::different_method()
{ return 1; }

int A::common_method()
{ return this->different_method()+1; }

int B::different_method()
{ return 2; }

int B::common_method()
{ return this->different_method()+1; }

what is the best way to do it?

One way is to make A and B inherit from a base class C, with the new methods:

int A::different_method()
{ return 1; }

int B::different_method()
{ return 2; }

int C::different_method()
{ return 0; }

int C::common_method()
{ return this->different_method()+1; }

but it is a little bit annoying that I have to also define the useless C::different_method. What is the best practice for such situations?

Questioner
DingoTim
Viewed
15
NutCracker 2020-01-31 17:32

Try using pure virtual function:

struct Base {
    virtual int different_method() = 0;

    int common_method() {
        return different_method() + 1;
    } 
};

struct Derived1 : Base {
    int different_method() override {
        return 1;
    }
};

struct Derived2 : Base {
    int different_method() override {
        return 2;
    }
};

Check it out live