Question

I like to have well defined interface in a few classes, for this I created pure virtual functions in an abstract class that each class needs to implement.
But I'm facing the problem that I can instantiate the classes so I have to create another class that inherit the interface class, and all the other classes needs to inherit from this base class. Here is the code for example:

The interface

class Interface
{
     virtual std::string getName() = 0;
}

class Base : public Interface
{
   virtual std::string getName(return std::string("Base") ;)
}

class A : public Base
{
  std::string getName(return std::string("A") ;)

}

class B : public Base
{
  std::string getName(return std::string("B") ;)

}

All this so i could in code to have the same type for A & B.
Can I just use the Interface class without the Base class?
Something like this:

class A : public Interface
{
  std::string getName(return std::string("A") ;)

}
Was it helpful?

Solution

You cannot instantiate the interface, but what you can do is have a pointer to the interface, pointing to an instance of an implementation:

class Interface { /* pure virtual methods */ };
class A : virtual public Interface { /* implement all pure virtual methods */ };
class B : virtual public Interface { /* implement all pure virtual methods */ };

Interface * i0 = new A();
Interface * i1 = new B();

This is a standard way of using polymorphic classes (although you might want to use smart pointers instead of raw pointers).

Edit: concerning the use of virtual inheritance, see here and here for more information.

OTHER TIPS

No they don't. All classes that inherit (directly or indirectly) from the interface must have the pure virtual function implemented somewhere in the inheritance tree in order to be instantiated.

So you can either implement the method in the base class, or your top class.

Also, your syntax is way off:

class A : public Interface
{
  std::string getName()
  {
      return std::string("A");
  }
};

The above should work even though it's not derived from Base, because you implement the pure virtual method from Interface.

Suggestion - make your getName method const.

You cannot create an instance of the base class if it has a pure virtual function as it is then an abstract base class. If you need to be able to instantiate this class don't have any pure virtual functions in it. Otherwise simply derive from it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top