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.
There are several options with different advantages and disadvantages.
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.
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.
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.
Other options. There may be other more specialized options depending on your requirements.
Related
I want to provide a stable API for a library I've written by providing a set of pure abstract classes.
Consider the following class hierarchy:
//Note: Destructors left out for readability
struct IBase{
virtual void something() = 0;
}
struct IDerivedA : public IBase{
virtual void another() = 0;
}
struct IDerivedB : public IBase{
virtual void another(int a) = 0;
}
There will be multiple implementations for these interfaces. To write an implementation, I would do:
struct Base : public IBase{
int x; //x is required to implement something()
virtual void something();
}
struct DerivedA : public IDerivedA, public Base{
virtual void another();
}
struct DerivedB : public IDerivedB, public Base{
virtual void another(int a);
}
This leads to the dreaded diamond problem, for which I see the following solutions:
Virtually inherit IBase in both IDerivedA and IDerivedB and just use multiple inheritance
Don't use Base at all and instead forward the calls to a helper class to avoid code duplication
Something like:
struct Base{
int x; //x is required to implement somethingImpl()
void somethingImpl();
}
struct DerivedA : public IDerivedA{
virtual void something(){ b.somethingImpl(); };
virtual void another();
private:
Base b;
}
struct DerivedB : public IDerivedB{
virtual void something(){ b.somethingImpl(); };
virtual void another(int a);
private:
Base b;
}
In case of 1), virtual inheritance would be required every time I use inheritance in the API layer.
In case of 2), I would need to wrap Base for every implementation class, which leads to code bloat.
I believe that there might be something fundamentally wrong in the design. Is there a general best practice for this specific case?
there's this code :
class Base{
public:
void disp(){
cout<<"base"<<endl;
}
};
class Der1:public Base{
public:
void test1(){
cout<<"der1 test1"<<endl;
}
};
class Der2:public Base{
public:
void test2(){
cout<<"der2 test2"<<endl;
}
};
class Der3:public Der1,Der2{
public:
void fun(){
cout<<"Der3 fun"<<endl;
}
};
int main()
{
Der3 d;
d.test1();
}
OUTPUT: der1 test1 //printed successfully
but for
int main()
{
Der3 d;
d.test2();
}
it gives error that Der2 is inaccessible ...
However when i change the code to
class Base{
public:
void disp(){
cout<<"base"<<endl;
}
};
class Der1:public Base{
public:
void test1(){
cout<<"der1 test1"<<endl;
}
};
class Der2:public Base{
public:
void test2(){
cout<<"der2 test2"<<endl;
}
};
class Der3:public Der2,Der1{ //***changed the order here***
public:
void fun(){
cout<<"Der3 fun"<<endl;
}
};
int main()
{
Der3 d;
d.test2();
}
it outputs: der2 Test2
Can someone explain what is happening here ?
It should be:
class Der3:public Der2, public Der1{
If you don't specify the access qualifier, it defaults to private.
Also because you have a common base in the two types inherited in Der3 you should use virtual inheritance in Der1 and Der2. This avoids replicating the common Base members (if any.)
class Der1:public virtual Base{...
class Der2:public virtual Base{...
You have to add the accessibility to each base class:
class Der3:public Der1, public Der2{
public:
void fun(){
cout<<"Der3 fun"<<endl;
}
};
When you switch the order Der2 is a public base but Der1 is private.
class Der3:public Der1,Der2 {
The 'public' there is only good for the next base class. You want to write:
class Der3: public Der1, public Der2 {
Also, it should be noted that this example also shows the deadly "diamond" inherience pattern, so it's designer clearly should be slapped.
By default, class inheritance is private. And so:
class Der3: public Der1, Der2
is the same as:
class Der3: public Der1, private Der2
You need to use public inheritance for both base classes:
class Der3: public Der1, public Der2
I'll try to make my intentions clear since there may be more than one approach to this. To start, I have an abstract base class FooBase with a virtual function SayHi(). Foo1 is one of many derived classes.
class FooBase {
public:
virtual void SayHi() = 0;
};
class Foo1 : public FooBase {
public:
virtual void SayHi() {
std::cout<<"Foo1 says Hi\n";
}
};
I also have a Component class and sometimes I would like to implement Foo.. classes as Components. I've used a template class so that any subclass of FooBase can have a Component wrapper.
class FooComponentBase : public Component {
public:
virtual FooBase& GetFoo() = 0;
};
template <class T>
class FooComponent : public FooComponentBase {
private:
T m_foo;
public:
virtual FooBase& GetFoo() {return m_foo;}
};
Now FooComponentBase is an interface to components containing any subclass of FooBase:
void DoTest() {
FooComponentBase* pFooComponent = new FooComponent<Foo1>;
pFooComponent->GetFoo().SayHi(); // "Foo1 says Hi"
delete pFooComponent;
}
So far so good, this works. But it might be neater if FooComponent were inherited from FooBase, so we don't need to go through GetFoo() to access FooBase's methods.
// Inherited version
class FooComponentBase : public Component {};
template <class T>
class FooComponent : public FooComponentBase, public T {};
Unfortunately, FooComponentBase has no access to FooBase even though all of its derived classes do;
void DoTest() {
FooComponentBase* pFooComponent = new FooComponent<Foo1>;
pFooComponent->SayHi(); // Error, FooComponentBase has no SayHi() function
delete pFooComponent;
}
I can't find a way to make this work. It seems like there ought to be a way, maybe using virtual inheritance;
class FooComponentBase : public Component, virtual public FooBase {};
But that won't compile either, since we can't instantiate an abstract class. I hope my intention is clear, I'd like to make FooComponentBase an abstract base class, like FooBase but with Component inheritance, so I can use it to access every flavor of FooComponent.
Is there a neat way to do this?
If you use virtual inheritance in one place, you have to use it everywhere if you want that same base implementation to be used:
class Foo1 : public virtual FooBase {
The other way, which is not as nice but might work out for you, would be to implement all of FooBase's functions in FooComponent:
class FooComponentBase : public Component, public FooBase {
};
template <class T>
class FooComponent : public FooComponentBase {
private:
T m_foo;
public:
void SayHi() {m_foo.SayHi();}
};
Or even:
class FooComponentBase : public Component, public FooBase {
};
template <class T>
class FooComponent : public FooComponentBase, public T {
public:
void SayHi() {T::SayHi();}
};
Consider this example of code:
class Base
{
public:
Base() {}
};
class Derived1 : public Base
{
public:
Derived1() : Base() {}
};
class Derived2 : public Base
{
public:
Derived2() : Base() {}
};
Is there any to make that Derived1 has-a Derived2 and Derived2 has-a Derived1?
The best solution would be by using a third class which has those two objects. But in case high performance is needed?
An example might be a two-way client-server application.
EDIT: Consider that that's just a summary example. In the real code each of the three classes could throw an exception; I made sure that the code is exception-safe, though.
You can accomplish a "has-a" relationship with a forward declaration which basically tells "this class exists, it's just not declared yet"
#include <iostream>
using namespace std;
class Base
{
public:
Base() {}
};
// Forward declaration
class Derived1;
class Derived2 : public Base
{
friend class Derived1;
public:
Derived2() : Base() {}
private:
Derived1 *ptr;
};
class Derived1 : public Base
{
public:
Derived1(Derived2& obj) : Base(), ptr(&obj) {
obj.ptr = this;
}
private:
Derived2 *ptr;
};
int main() {
Derived2 obj2;
Derived1 obj1(obj2);
return 0;
}
http://ideone.com/RVU8AR
This way the two classes can communicate with each other. Notice the private pointers and the initialization into the constructor. With the "friend" declaration one class is able to modify the other class's private members.
Each class can hold a pointer:?
class Derived1
Derived2 *p_d2;
class Derived2
Derived1 *p_d1;
when does ambiguity arise in multiple inheritance?
When you have replicated base class in several paths of inheritance and you are trying to cast to it or call its member-function.
struct A { };
struct B : A { };
struct C : A { };
struct D : B, C { }; // has replicated A as the base class
D d;
A* a = static_cast<A*>(&d); // oops
The problem has several remedies which depend on the context heavily (using virtual base classes, just refine the aforementioned cast, etc.)
More info here, especially here.
One famous example of ambiguity in multiple inheritance is the so-called Diamond Problem.
Summary:
"In object-oriented programming languages with multiple inheritance and knowledge organization, the diamond problem is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If a method in D calls a method defined in A (and does not override the method), and B and C have overridden that method differently, then from which class does it inherit: B, or C?"
You can find details here: Wikipedia: Diamond Problem
struct Base{
void foo(){
}
};
struct Derived1 : public Base{
};
struct Derived2 : public Base{
};
struct Final : public Derived1, public Derived2{
};
int main(){
Final f;
f.foo();
}
See on Ideone. To fix, simply use virtual inheritance:
struct Derived1 : virtual public Base{
};
struct Derived2 : virtual public Base{
};
Another possibility for ambigouty is the following:
struct Base1{
void foo(){
}
};
struct Base2{
void foo(){
}
};
struct Final : public Base1, public Base2{
};
int main(){
Final f;
f.foo();
}
Again, on Ideone. To fix, simple make do the following in Final:
struct Final : public Base1, public Base2{
using Base1::foo;
// or
// using Base2::foo;
};
When it makes names used unclear
class baseX
{
private:
void* callA();//will never be ambiguous.
protected:
void* callB();
public:
void* callC();
}
class baseY
{
private:
void* callA();//will never be ambiguous.
protected:
void* callB();
public:
void* callC();
}
class derived: public baseX, public baseY
{
void someMethod()
{
void* x = baseX::callB();//not ambiguous
void* y = baseY::callB();//not ambiguous
void* z = callB();//ambiguose
}
}
void someFunction(derived& d)
{
void* x = d.CallC();//ambiguous
}
Ambiguity can also happen when the same class is the base through more than one route:
class Base
{
public void call();
}
class DerivedX : public Base
{
}
class DerivedY : public Base
{
}
class GrandChild : public DerivedX, public DerivedY //What does call() do?
{
}
This can be solved with virtual bases:
class Base
{
public void call();
}
class DerivedX : public virtual Base
{
}
class DerivedY : public virtual Base
{
}
class GrandChild : public DerivedX, public DerivedY //only one "Base" class in inheritance, shared between DerivedX and DerivedY
{
}