2
class A
{
      public:
             virtual void display_A(A* obja)
             {
                     cout<<"Class A"<<endl;
             }
};
class B:public A
{
      public:
             void display_A(B* objb)
             {
                     cout<<"Class B"<<endl;
             }
};

int main()
{
    A AOBJ;
    B BOBJ;
    A *obja = new B();
    obja->display_A(&AOBJ);
    obja->display_A(&BOBJ);
    return 0;
}

There is a virtual function in class A having parameter as A* and we are overriding the same function in the derived class B with parameter B*.

I have created a pointer obja (pointer to class A) which is pointing to derived class object B. When I am calling the function display_A with obja pointer with argument as class A object pointer and class B object pointer, I am getting o/p as

Class A
Class A

I am unable to understand why I am getting that o/p.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Khalid
  • 19
  • 3
  • anyhow you might rethink the design. You use one objects display method to display another object. Wouldnt it be better if the objects use their own display method to display (in which case there is no need to pass the pointer explicitly as parameter) ? – 463035818_is_not_an_ai Mar 26 '16 at 10:10
  • Possible duplicate of [C++ covariance in parameters](http://stackoverflow.com/questions/11821158/c-covariance-in-parameters) – Jean-Baptiste Yunès Mar 26 '16 at 10:56

2 Answers2

6

It's not overriding because the parameter's type is not the same.

If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same

name
parameter type list (but not the return type)
cv-qualifiers
ref-qualifiers 

Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).

Using override specifier could help you find the error at compile time.

Specifies that a virtual function overrides another virtual function.

In a member function declaration or definition, override ensures that the function is virtual and is overriding a virtual function from the base class. The program is ill-formed (a compile-time error is generated) if this is not true.

class B:public A
{
      public:
             void display_A(B* objb) override
             //                      ^^^^^^^^
             {
                     cout<<"Class B"<<endl;
             }
};
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

When calling display_A via an A*, either a virtual func of A or B or a non-virtual func of A is called. Since the prototypes are different, the only function matching this criteria is A::display_A.

Jacques de Hooge
  • 6,750
  • 2
  • 28
  • 45