Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it perfectly legal to declare a pure virtual function twice (in two classes in an hierarchy)

The question's title is pretty clear. Here's what I mean by example:

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

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

class C: public B
{
public:
    virtual void f() {}
};
like image 601
Kiril Kirov Avatar asked Nov 22 '13 12:11

Kiril Kirov


People also ask

What is the proper way to declare pure virtual?

You declare a pure virtual function by using a pure specifier ( = 0 ) in the declaration of a virtual member function in the class declaration.

Is it always mandatory to implement or define all the pure virtual function of the base class into derived class?

Yes, that's fine ... you only need to implement any pure virtual functions in order to instantiate a class derived from an abstract base class.

Can pure virtual function be protected?

However, with pure virtuals, there is no base implementation... So isn't it functionally equivalent to declare a pure virtual as either private or protected? A protected pure virtual doesn't make sense because you can't ever invoke the base class's corresponding method.


2 Answers

Yes this is legal because there are not the same functions at all. The B::f() function is an overriding of A::f(). The fact that f() is virtual in both cases is not entering into account.

like image 144
perror Avatar answered Sep 29 '22 09:09

perror


Yes, it is perfectly legal.

In most situations the declaration on f() in B doesn't change the meaning of the program in any way, but there's nothing wrong with a little redundancy.

Recall that the "= 0" means only that the class may not be instantiated directly; that all pure virtual function must be overridden before an object can be instantiated.

You can even provide a definition for a pure virtual function, which can be called on an instance of a subclass. By explicitly declaring B::f(), you leave open the option of giving a definition for B::f().

like image 36
Andy Jewell Avatar answered Sep 29 '22 07:09

Andy Jewell