Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual qualifier in derived class

Tags:

c++

Does the virtual qualifier to a virtual function of base class, in the derived class makes any difference ?

class b
{
   public:
   virtual void foo(){}
};

class d : public b
{
  public:
  void foo(){ .... }
};

or

class d : public b
{
  public:
  virtual void foo(){ .... }
}; 

Is there any difference in these two declarations, apart from that it makes child of d make aware of virtuality of foo() ?

like image 437
amneet Avatar asked Aug 17 '11 19:08

amneet


People also ask

Can virtual function be declared in derived class?

The virtual keyword can be used when declaring overriding functions in a derived class, but it is unnecessary; overrides of virtual functions are always virtual. Virtual functions in a base class must be defined unless they are declared using the pure-specifier.

Is it mandatory to override virtual function in derived?

It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. A class may have virtual destructor but it cannot have a virtual constructor.

Can a virtual function be declared as protected or private in the derived classes?

A virtual function can be private as C++ has access control, but not visibility control. As mentioned virtual functions can be overridden by the derived class but under all circumstances will only be called within the base class.

Can virtual function be inherited?

Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called. A is the base class for B,C,D.


1 Answers

It makes no difference. foo is virtual in all classes that derive from b (and their descendants).

From C++03 standard, §10.3.2:

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name and same parameter list as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.

like image 95
Mat Avatar answered Sep 30 '22 11:09

Mat