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?
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
Prefer
override
overvirtual
to indicate overridden methods. compiler might help to spot "typos" in that case.@Jarod42 Thanks. I appreciate your suggestion. I will update my answer.