1

If I have a hierarchy of C++ classes where the base class has a member function that is declared as virtual, but derived classed do not declare that function as virtual, how far into the class hierarchy does the virtualization carry. For example, given the code is the return value of MyFunc2 well defined?

class A
{
public:
  virtual int x() { return 1; }
}

class B : public A
{
public:
  int x() { return 2; }
};

class C: public B
{
public:
  int x() { return 3; }
};

int MyFunc1(f &A)
{
 return f.x();  
}

int MyFunc2(f &B)
{
 return f.x();
}

int MyFunc3()
{
 C c;
 return MyFunc1(c);
}

int MyFunc4()
{
 C c;
 return MyFunc2(c);
}

From similar question here, it would appear that the virtual characteristic is propagated forward to all classes once it is virtual in the base class, but I'm wondering how well defined this is, specifically is B.x() virtual by implication of being derived from A.

Community
  • 1
  • 1
SmacL
  • 22,555
  • 12
  • 95
  • 149

2 Answers2

5

Overrides in subclasses are implicitly virtual too. You can specify the virtual keyword again, but it does not make any difference, although it's often considered good practice. It is absolutely "well defined" in the standard.

Starting C++11, you have an even better option: you can tag virtual methods in subclasses with override to ensure they actually override something. This prevent not actually overriding parent methods because of a small prototype difference and will trigger errors if you change the base virtual prototype but forget to adapt the overrides.

mefyl
  • 264
  • 1
  • 6
1

Yes, the virtual characteristic is "propagated" (to use your wording) to all derived classes. If derived classes declare and define a member function with the same signature as an inherited virtual function, they override it.

C++11 introduced the final modifier which derived classes can use to prevent their descendents from further-overriding an inherited virtual function. However, the function is still technically virtual (e.g. given a pointer to base, a polymorphic call of p->func() calls the func() corresponding to the actual type of the object) .... it just cannot be overridden.

Peter
  • 35,646
  • 4
  • 32
  • 74