1
class A
{
public:
void test ()
{
cout<<"In A";
}
};
class B :public A
{
public:
void test ()
{
cout<<"In B";
}
};
class C : public B
{

public:
int c;
};
int main()
{
C c;
c.test();
}

The result is: In B...
sandeep
  • 205
  • 1
  • 3
  • 5
  • Hang on a sec....you posted the exact same question 10 minutes later....double posting in the hope of getting an answer is frowned upon.... http://stackoverflow.com/questions/2483260/baffling-behavior – t0mm13b Mar 20 '10 at 13:55
  • 1
    @tommieb75: They are actually different questions. This one is about function overriding; the other one is about pointer conversions. – CB Bailey Mar 20 '10 at 14:01

1 Answers1

5

No, it is not overriding, but rather hiding the original method.

Polymorphic behavior in C++ is restricted to the methods declared virtual, and each implementation of that method in a class hierarchy is called an override of the method.

struct base {
   virtual void foo();
   void bar();
};
struct derived : base {
   virtual void foo();
   void bar();
};

In the example base::foo and derived::foo are overrides. When you use a class of type derived through a pointer or reference of type base, the final override method will be called (the lowest one in the hierarchy: in this case derived::foo). The important point here is that the call is through a pointer or reference to base:

void test() {
   derived d;
   base &b = d;
   b.foo(); // derived::foo() <- final overrider
   b.bar(); // base::bar()    <- non-virtual, no override
   d.bar(); // derived::bar() <- hides the method in base
}

What happens in the case of bar (or in your case) is that when the compiler finds the call d.bar() it needs to determine what method to call. To locate the method it will first look inside derived declaration and it will find derived::bar() (which is unrelated to base::bar()) and it will use that method without checking higher in the class hierarchy. If you need to call the method higher in the hierarchy you can do it by either getting a reference to the higher type or fully qualifying the method you want to call.

Note that hiding does not only happen when the signature matches completely, but in all cases where the compiler finds a method with the same name:

struct base {
   void bar();
};
struct derived : base {
   void bar( int );
};
void test() {
   derived d;
   base & b;

   b.bar();    // ok: base::bar()
   d.bar(1);   // ok: derived::bar(int)
   //b.bar(1); // error: base has no bar method that takes an integer
   //d.bar();  // error: derived::bar takes an integer, base::bar is hidden
   d.base::bar(); // ok: fully qualifying tells the compiler where to look
}
David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
  • 1
    You may want an example with Base::bar(int) and Derived::bar(double), calling d.bar(int(1)) and getting Derived::bar(double) as Base::bar(int) is hidden. Always a fun "gotcha" for newbies... – Mr.Ree Mar 20 '10 at 14:10