1

I have a naive C++ inheritance class question. I have one base class Base, two derived classes DerivedA and DerivedB and two other distinct classes A and B which share the names of some methods.

Ideally I would like to design methods in the base class that use the methods of A and B. My attempt is the following

#include <cstdio> class A{ public : A(){}; void speak(){printf("hello A\n");}; }; class B{ public : B(){}; void speak(){printf("hello B\n");}; }; class Base{ public: Base(){}; void method(){property.speak();} A property; }; class DerivedA : public Base{ public: using Base::Base; A property; }; class DerivedB : public Base{ public: using Base::Base; B property; }; int main(int argc, char *argv[]){ DerivedA da; DerivedB db; da.property.speak(); db.property.speak(); // Attempting to call the shared method on the two distinct properties da.method(); db.method(); } 

Could you point me to a better design ? I suspect I should use templates but I am not sure how.

1 Answer 1

1

There are several options with different advantages and disadvantages.

  1. You can make the base class a template like this:
template<class Property> class Base{ public: Base(){}; void method(){property.speak();} Property property; }; class DerivedA : public Base<A>{ }; class DerivedB : public Base<B>{ }; 

It is clear and simple, but notice that DerivedA and DerivedB in this case have no common base class, so you can't, e.g. put pointers to them in the same container.

  1. You can use polymorphism.
class Base{ public: virtual ~Base() {} virtual void method() = 0; }; class DerivedA : public Base{ public: A property; void method() override { property.speak(); } }; class DerivedB : public Base{ public: B property; void method() override { property.speak(); } }; 

This is a bit more complex, involves some code duplication and requires more resources (to store virtual table e.g.), but now the classes really have a common ancestor.

  1. Combine templates and polymorphism
class Base{ public: virtual ~Base() {} virtual void method() = 0; }; template<class Property> class Derived: public Base { public: Property property; void method() override { property.speak(); } }; using DerivedA = Derived<A>; using DerivedB = Derived<B>; 

This is actually option #2, but with no code duplication: we make the compiler generate code for us using templates.

  1. Other options. There may be other more specialized options depending on your requirements.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.