开发者

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

开发者 https://www.devze.com 2022-12-24 02:37 出处:网络
class A { public: void test () { cout<<\"In A\"; } }; class B :public A { public: void test () { cout<<\"In B\";
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.te开发者_运维技巧st();
}

The result is: In B...


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号