I have the following condition:
An absract base class with many pure virtual functions:
interface IBase
{
virtual void foo1() = 0;
virtual void foo2() = 0;
virtual void foo3() = 0;
virtual void foo4() = 0;
virtual void foo5() = 0;
// ...
virtual void fooN() = 0;
};
Two small interfaces that inherit it:
Version-A:
interface IBaseExt_A :
public IBase
{
virtual void foo_A() = 0;
};
Version-B:
interface IBaseExt_B :
public IBase
{
virtual void foo_B() = 0;
};
I create base class that implements all of the IBase interface functions:
class CBase :
public IBase
{
public:
virtual void foo1() { /* Do something... */}
virtual void foo2() { /* Do something... */}
virtual void foo3() { /* Do something... */}
virtual void foo4() { /* Do something... */}
virtual void foo5() { /* Do something... */}
// ...
virtual void fooN() { /* Do something... */}
};
Now, I want to implement both derived versions with minimal code.
I was hoping to do something like:
class CBaseExt_A :
public IBaseExt_A,
public CBase
{
public:
virtual void foo_A() { /* Do something... */}
};
Apparently this gives error:
C2259: 'CBaseExt_A': cannot instantiate abstract class...These errors refer to all IBase interface functions.
I know I can solve it the long way by delegating all IBase functions to CBase implementation:
class CBaseExt_A :
public IBaseExt_A,
public CBase
{
// IBase implementation:
public:
virtual void foo1() { CBase::foo1();}
virtual void foo2() { CBase::foo2();}
virtual void foo3() { CBase::foo3();}
virtual void foo4() { CBase::foo4();}
virtual void foo5() { CBase::foo5();}
// ...
virtual void fooN() { CBase::fooN();}
// IBaseExt_A implementation:
public:
virtual void foo_A() { /* At last - do what we came here for...*}
};
But this makes my small class CBaseExt_A become big and complex.
Is there a way how to avoid all this manual delegation coding?
Many thanks, PazO
You should use the following code:
interface IBase
{
virtual void foo() = 0;
......
};
class CBase : virtual public IBase
{
void foo() { }
......
};
interface IBaseExt_A : virtual public IBase
{
virtual void foo_A() = 0;
};
struct CBaseExt_A : public IBaseExt_A, public CBase
{
virtual void foo_A() { /* Do something... */ }
};
Note that both places where the IBase class is inherited should be marked as virtual.
I think you should specify one of the two inheritance to be virtual.
That is a diamond inheritance where
IBase is the top level
IBaseExt_A and CBase are the middle level
CBaseExt_A is the bottom level
so in CBaseExt_A you want to specify from which path implement the top level, I would say that you may want to specify CBase inheritance in IBaseExt_A to be public virtual instead of just public.
class CBaseExt_A :
public IBaseExt_A,
public virtual CBase
{
public:
virtual void foo_A() { /* Do something... */}
};
Related
I come from a Delphi and C# background so I understand interfaces from their perspectives. I have been doing C++ for a few years and still learning interfaces from its perspective.
In my application I have a situation where I need classes that implement multiple interfaces (i.e. inherit multiple pure abstract classes) to indicate various behaviors that are supported by each class. This is not exactly ISP, but it is close enough that it is the same problem.
The behavior interfaces do not inherit from each other. There is no hierarchy.
Delphi and C# do this without breathing heavy but I am trying to figure out how this is done in C++. (Also, for now, I am limited to C++11.)
I have explored dynamic_pointer_cast, static_pointer_cast but they require an inheritance hierarchy.
I looked at reinterpret_pointer_cast, but it's not available in C++11.
I have tried using a root interface that my behavior interfaces inherit (similar to IUnknown in COM or IInterface in Delphi), creating an inheritance hierarchy, but then I run into the diamond problem.
I have seen some suggestions for adding methods to the base interface to return references to each behavior interface, but that's a kind of coupling I really don't want, since I may need to add other behaviors and classes that implement them later.
Here is some code, that I have not compiled, showing a simple example of what I am trying to do.
class IBase
{
public:
virtual void DoBaseStuff() = 0;
}
class IBehaviorA
{
public:
virtual void DoBehaviorA() = 0;
}
class IBehaviorB
{
public:
virtual void DoBehaviorB() = 0;
}
class Base : public IBase
{
public:
Base() {}
virtual ~Base() {}
virtual void DoBaseStuff() { /* ... */ }
}
class JustA : public IBase, public IBehaviorA
{
public:
JustA() {}
virtual ~JustA() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorA() { /* ... */ }
}
class JustB : public IBase, public IBehaviorB
{
public:
JustB() {}
virtual ~JustB() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorB() { /* ... */ }
}
class AandB : public IBase, public IBehaviorA, public IBehaviorB
{
public:
AandB() {}
virtual ~AandB() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorA() { /* ... */ }
virtual void DoBehaviorB() { /* ... */ }
}
void ProcessAllBehaviorA(std::vector<std::shared_ptr<IBase>> bases)
{
for (auto& base : bases)
{
std::shared_ptr<IBehaviorA> behaviorA
= SOME_KIND_OF_CAST<IBehaviorA>(base);
if (behaviorA != nullptr)
{
behaviorA->DoBehaviorA();
}
}
}
void main()
{
std::vector<std::shared_ptr<IBase>> bases;
bases.push_back(std::shared_ptr<IBase>(new Base()));
bases.push_back(std::shared_ptr<IBase>(new JustA()));
bases.push_back(std::shared_ptr<IBase>(new JustB()));
bases.push_back(std::shared_ptr<IBase>(new AandB()));
ProcessAllBehaviorA(bases);
}
I am trying to figure out what to do where the SOME_KIND_OF_CAST placeholder is in the ProcessAllBehaviorA method.
I am sure that I cannot be the first person to try to do this.
How do other people implement the Interface Segregation Principle (or similar patterns like mine) using smart pointers in C++?
I have explored dynamic_pointer_cast, static_pointer_cast but they require an inheritance hierarchy.
Your code does have an inheritance hierarchy, so std::dynamic_pointer_cast would work just fine! I have added some behavior to your code, and it works as expected.
#include <memory>
#include <vector>
#include <iostream>
class IBase
{
public:
virtual void DoBaseStuff() = 0;
};
class IBehaviorA
{
public:
virtual void DoBehaviorA() = 0;
};
class IBehaviorB
{
public:
virtual void DoBehaviorB() = 0;
};
class Base : public IBase
{
public:
Base() {}
virtual ~Base() {}
virtual void DoBaseStuff() { /* ... */ }
};
class JustA : public IBase, public IBehaviorA
{
public:
JustA() {}
virtual ~JustA() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorA() { std::cout << "I am just A!" << std::endl; }
};
class JustB : public IBase, public IBehaviorB
{
public:
JustB() {}
virtual ~JustB() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorB() { /* ... */ }
};
class AandB : public IBase, public IBehaviorA, public IBehaviorB
{
public:
AandB() {}
virtual ~AandB() {}
virtual void DoBaseStuff() { /* ... */ }
virtual void DoBehaviorA() { std::cout << "I am A and B" << std::endl; }
virtual void DoBehaviorB() { /* ... */ }
};
void ProcessAllBehaviorA(std::vector<std::shared_ptr<IBase>> bases)
{
for (auto& base : bases)
{
std::shared_ptr<IBehaviorA> behaviorA
= std::dynamic_pointer_cast<IBehaviorA>(base);
if (behaviorA != nullptr)
{
behaviorA->DoBehaviorA();
}
else {
std::cout << "Requested pointer does not implement A." << std::endl;
}
}
}
void main()
{
std::vector<std::shared_ptr<IBase>> bases;
bases.push_back(std::shared_ptr<IBase>(new Base()));
bases.push_back(std::shared_ptr<IBase>(new JustA()));
bases.push_back(std::shared_ptr<IBase>(new JustB()));
bases.push_back(std::shared_ptr<IBase>(new AandB()));
ProcessAllBehaviorA(bases);
}
Output:
Requested pointer does not implement A.
I am just A!
Requested pointer does not implement A.
I am A and B
By the way you missed the semicolons at the end of class definitions.
For code below, are there any other ways to access a method in base through interface?
struct Base {
void funct_base() {
printf("Common function for class Foo and class Bar\n");
}
};
struct IFoo {
virtual ~IFoo() {}
virtual void funct_a() = 0;
// would like to access Base::bunct_base() from here
};
struct Foo : public Base, public IFoo {
virtual void funct_a() {
printf("I am Foo:: funct A\n");
}
};
class IBar {
virtual ~IBar() {}
virtual void funct_a() = 0;
// would like to access Base::bunct_base() from here
};
class Bar : public Base, public IBar {
virtual void funct_a() {
printf("I am Bar:: funct A\n");
}
};
I know this can be done, but I just do not like the wrapper, it does not seem clean:
struct IBar {
virtual ~IBar() {}
virtual void funct_a() = 0;
virtual void funct_base() = 0;
};
struct Bar : public Base {
virtual void funct_a() {
printf("I am Bar:: funct A\n");
}
virtual void funct_base() {
Base::funct_base();
}
};
EDIT:
The question is, there is one base class, and two different derived classes that inherit from the same base class. Is there a way to access a base class method through derived class interface without adding a base class method wrapper?
Use a abstract base class IBase with a Abstract method funct_base and make the interface class a Virtual base classes of the classes Base, IFoo and IBar:
struct IBase {
virtual void funct_base() = 0;
};
struct Base : public virtual IBase {
virtual void funct_base() override { printf("Common function for class Foo and class Bar\n"); }
};
struct IFoo : public virtual IBase {
virtual void funct_a() = 0;
};
struct Foo : public IFoo, public Base {
virtual void funct_a() override { printf("I am Foo:: funct A\n"); }
};
class IBar : public virtual IBase {
virtual void funct_a() = 0;
};
class Bar : public IBar, public Base {
virtual void funct_a() override { printf("I am Bar:: funct A\n"); }
};
I have 3 interface (pure virtual) classes like this
class A {
virtual void M1() = 0;
virtual void M2() = 0;
};
class B : public A {
virtual void M3() = 0;
};
class C : public A {
virtual void M4() = 0;
};
I have the implementers like this
class Aimpl : A {
void M1 () override {};
void M2 () override {};
}
class Bimpl: public Aimpl, public B{
void M3() override {};
}
class Cimpl: public Aimpl, public C{
void M4() override {};
}
and
Bimpl b = Bimpl();
b.M2() // Error. M2 is ambigous. Can be from Aimpl or A
what's a simple way to fix this? I want to be able to pass around B or C in functions rather than Bimpl
Essentially, you have two different M2 methods in Bimpl: Aimpl::M2 and B::M2. You have run into the diamond-inheritance problem.
To fix it, you should use virtual inheritance. This question provides a very good overview. Essentially, you should use something like this:
class A {
virtual void M1() = 0;
virtual void M2() = 0;
};
class B : public virtual A {
virtual void M3() = 0;
};
class C : public virtual A {
virtual void M4() = 0;
};
class Aimpl : public virtual A {
void M1 () override {};
void M2 () override {};
};
class Bimpl: public virtual Aimpl, public virtual B {
void M3() override {};
};
class Cimpl: public virtual Aimpl, public virtual C {
void M4() override {};
};
Note that I'm not super super familiar with virtual inheritance, so this may or may not be the best way to apply virtual inheritance.
Please refer the following example.
using namespace std;
//Base interface
class IBase
{
public:
virtual void BaseMethod1() = 0;
virtual void BaseMethod2() = 0;
};
class IEntity1 : public IBase
{
public:
virtual void Entity1Method1() = 0;
virtual void Entity1Method2() = 0;
};
class Entity1 : public IEntity1
{
public:
Entity();
//IBaseMethods
void BaseMethod1();
void BaseMethod2();
//IEntityMethods
void Entity1Method1();
void Entity1Method2();
//EntityMethods
void Method1();
void Method2();
};
In the above example, for all other entities deriving from IBase needs to implement BaseMethod1() and BaseMethod2().Because of which lots of code duplication is happening? Is there anyway where we can avoid redundant implementation of IBase methods in entities deriving from it?
You can use virtual inheritance in combination with a default base implementation class to encapsulate your default base behavior, and have it be only inherited by the concrete classes you want, like follows:
using namespace std;
//Base interface
class IBase
{
public:
virtual void BaseMethod1() = 0;
virtual void BaseMethod2() = 0;
};
class IEntity1 : virtual public IBase
{
public:
virtual void Entity1Method1() = 0;
virtual void Entity1Method2() = 0;
};
class BaseImpl : virtual public IBase
{
public:
virtual void BaseMethod1()
{
...
}
virtual void BaseMethod2()
{
...
}
}
class Entity1 : public IEntity1, public BaseImpl
{
public:
Entity1();
//IEntityMethods
void Entity1Method1();
void Entity1Method2();
//EntityMethods
void Method1();
void Method2();
};
There is, however, a runtime cost associated with virtual inheritance. Multiple inheritance also comes with some structural issues, e.g. base class construction.
You can even have some fun with template classes to make your class composition more modular:
template<typename TEntity, typename TBaseImpl>
class ConcreteEntity: public TEntity, public TBaseImpl
{
public:
ConcreteEntity() {}
};
class ConreteEntity1 : public ConcreteEntity<IEntity1, BaseImpl>
{
public:
ConreteEntity1();
//IEntityMethods
void Entity1Method1();
void Entity1Method2();
//ConreteEntity1 Methods
void Method1();
void Method2();
};
You could make a function that is called in BaseMethod1() implementations that are the same.
Something like this:
void BaseMethod1_common();
class Entity1 : public IEntity1
{
public:
Entity();
//IBaseMethods
void BaseMethod1() { BaseMethod1_common(); }
void BaseMethod2();
//IEntityMethods
void Entity1Method1();
void Entity1Method2();
//EntityMethods
void Method1();
void Method2();
};
First of all IBase deserves a virtual destructor.
Declare it pure virtual and define IBase:BaseMethod1() and
IBase::BaseMethod1().
If your intention is to hide implementation, then the only option would be to release the code as a library and then share only the header file among the other developers.
Implementing a global function, or using multiple inheritance as suggested still mean that your implementation is exposed.
However, if the intent is to reduce coupling among the various classes, there's another option :
Create a class that has the actual shared implementation, and then another class which will be an interface to it.
This interface class will then be the base class for other derived entities.
Example code is shown below :
//First Header and Cpp file
class Base_private
{
public:
BaseImpl(arguments);
~BaseImpl();
void BaseMethod1() {
//Implementation
}
void BaseMethod2() {
//Implementation
}
};
//Second Header and Cpp file
class BaseInterface
{
public:
BaseInterface(arguments);
~BaseInterface();
void BaseMethod1() {
m_pBase->BaseMethod1();
}
void BaseMethod2() {
m_pBase->BaseMethod2();
}
private:
Base_private* m_pBase;
};
class Entity : public BaseInterface
{
public:
Entity(arguments);
~Entity();
void Method1();
void Method2();
};
I can't figure out how to call a base class method from a derived class method but concurrently applying this method call at an object passed as argument.
What I mean is this:
class Animal
{
virtual void eat(Animal& to_be_eaten) = 0;
};
class Carnivores: public Animal
{
virtual void eat(Animal& to_be_eaten) { /*implementation here*/}
};
class Wolf : public Carnivores
{
virtual void eat(Animal& to_be_eaten)
{ /*call eat method(of Base class) of Base to_be_eaten here*/ }
}
I thought of something like this
dynamic_cast<Carnivores&>(to_be_eaten).eat(*this) //and got a segmentation fault
Is there any way for this to be done?
Thank you!
New edit::
Updated the code
As simple as:
class Derived : public Base {
virtual void eat(Animal& to_be_eaten) {
Base::eat(to_be_eaten);
// do anything you want with to_be_eaten here.
}
};
EDIT: This works for me:
class Animal
{
virtual void eat(Animal& to_be_eaten) = 0;
};
class Carnivores: public Animal
{
virtual void eat(Animal& to_be_eaten) { /*implementation here*/}
};
class Wolf : public Carnivores
{
virtual void eat(Animal& to_be_eaten)
{
Carnivores *c = dynamic_cast<Carnivores*>(&to_be_eaten);
if(c)
c->Carnivores::eat(*this);
}
}
Note that i had to make Base::eat public in order to call it from Derived.
If I understand correctly, what you want is not to use a virtual call on the parameter object (to_be_eaten). I think only an object can do that for himself. I don't think there's a way for other objects to do it for him.
class Base
{
public:
virtual eat(Base& to_be_eaten);
protected:
virtual callEatNonVirtual(Base& other) = 0;
};
class Derived1 : public Base
{
public:
virtual eat(Base& to_be_eaten)
{
to_be_eaten.callEatNonVirtual(*this);
}
protected:
virtual callEatNonVirtual(Base& other)
{
Base::eat(other);
}
};
class Derived2 : public Base
{
public:
virtual eat(Base& to_be_eaten)
{
to_be_eaten.callEatNonVirtual(*this);
}
protected:
virtual callEatNonVirtual(Base& other)
{
Base::eat(other);
}
};