Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure virtual methods in derived abstract class

Say we have this:

class A
{
   public:
   virtual void foo() = 0;
};

class B: public A
{
   public:
   virtual void foo() = 0;
};

The compiler throws no error, I guess its because B is also an abstract class and as such it does not have to implement foo from A. But what does such a construct mean?

1) Does foo from B hide foo from A?

2) The first class which inherits from B and is not an abstract class, does it have to provide two implementations like:

class C: public B
{
   public:
   virtual void A::foo() {};
   virtual void B::foo() {};
};

The compiler only complains if the implementation of B::foo() is missing, but it does not complain about a missing A::foo().

All in all: is this a way to hide pure virtual methods?

like image 559
Juergen Avatar asked Mar 24 '13 20:03

Juergen


1 Answers

When you first declare:

class A
{
   public:
   virtual void foo() = 0;
};

you are declaring the method foo public, virtual and pure. When a class contains at least a pure method it's called abstract. What does it mean? It means that the class cannot be instantiated because it needs the pure methods implementations.

You can obviously inherit from an abstract class (I'd say that you are forced to do that, otherwise what would be the need of an abstract class you are not using, except for providing an interface to inherit from?) and you can also inherit from an abstract class and not implement some or all of the pure methods of the parent class; in this case the child class is abstract as well, which is the case of your class B:

class B: public A
{
   public:
   virtual void foo() = 0;
};

In B you could easily omit the virtual void foo() = 0; declaration because the definition is already inherited from the base class. In this case class B is an abstract class and therefore cannot be instantiated, just like A.

To answer your questions more directly:

Does foo from B hide foo from A?

No, it does not. They both are declaring a pure method (which is in fact the same method), therefore there's nothing to really hide.

The first class which inherits from B and is not an abstract class, does it have to provide two implementations like the one provided?

No, of course not. As stated above, they are the same method, therefore if class C have to provide an implementation for foo it should just implement foo:

class C: public B
{
   public:
   virtual void foo() {};
};
like image 112
Shoe Avatar answered Oct 19 '22 22:10

Shoe