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

StackOverflow https://stackoverflow.com/questions/20145009

  •  03-08-2022
  •  | 
  •  

Question

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() {}
};
Was it helpful?

Solution

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.

OTHER TIPS

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().

These three f() functions are difference but it is legal to declare same virtual function in two class because f() in A is overridden in F() in B. It function call depends on the class object.

so as according to above code , you do not have permission to create an instance of class A and B. hence every time the function define inside class C will be called.

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