1

Possible Duplicates:
C++ : implications of making a method virtual
Why is 'virtual' optional for overridden methods in derived classes?

I wonder, what is documented behavior in the following case:

You have

class A
{
 virtual void A()
 {
   cout << "Virtual A"<<endl;
 }
 void test_A()
 {
   A();
 }
}

class B: public A
{
  void A()
  {
   cout << "Non-virtual A in derived class"<<endl;
  }

  void test_B()
  {
    A();
  }
}

A a; B b;
a.test_A();
b.test_A();
b.test_B();

What it supposed to do according to C++ standard and why? GCC works like B::A is also also virtual.

What shoudl happen in general when you override virtual method by non-virtual one in derived class?

Community
  • 1
  • 1
BarsMonster
  • 6,483
  • 2
  • 34
  • 47

4 Answers4

3

The sub-class member function is implicitly virtual if a virtual base-class member function with the same name and signature exists.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
2

The code should not compile as you cannot name a method with the name of the class. But regarding what I understand that is your real question:

Will making a method virtual imply that the same method in all the derived classes is virtual even if the virtual keyword is not present?

The answer is yes. Once a method is declared virtual in a class, then all overrides of that method will be virtual, and the virtual keyword is optional in derived classes (even if I recommend typing it, if only for documentation purposes). Note that for a method in a derived class to be an override it has to have the same name and signature, with only potential difference being a covariant return type:

struct A {};
struct B : A {};
struct base {
   virtual A* foo();
   virtual A* bar();
};
struct derived : base {
   virtual B* foo();    // override, covariant return type
   virtual int bar();   // not override, return type is not covariant
   virtual A* bar(int); // not override, different argument list
};
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
0

According to standard it should be

A a; B b;
a.test_A();  //"Virtual A"
b.test_A(); //Non-virtual A in derived class
b.test_B(); //Non-virtual A in derived class
Chubsdad
  • 24,777
  • 4
  • 73
  • 129
yozhik
  • 4,644
  • 14
  • 65
  • 98
0

This code is ill-formed. A constructor cannot have a return type (as you have done for the constructor of 'A'). Also a constructor cannot be virtual.

After fixing A's constructor, class B is ill-formed as the constructor of A is private.

So, there are many problems with this code (including missing semicolons at the class definitions).

Chubsdad
  • 24,777
  • 4
  • 73
  • 129