Why the function from immediate parent is called and not from grandparent class. Is this called function overriding?

╄→尐↘猪︶ㄣ 提交于 2019-12-14 03:59:22

问题


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...

回答1:


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
}


来源:https://stackoverflow.com/questions/2483227/why-the-function-from-immediate-parent-is-called-and-not-from-grandparent-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!