开发者

C++: Is "Virtual" inherited to all descendants

Assume the following simple case (notice the location of virtual)

class A {
    virtual void func();
};

class B : public A {
    void func();
};

class C : public B {
    void func();
};

Would the fo开发者_如何学Cllowing call call B::func() or C::func()?

B* ptr_b = new C();
ptr_b->func();


  1. Your code is invalid C++. What are the parentheses in class definition?
  2. It depends on the dynamic type of the object that is pointed to by pointer_to_b_type.
  3. If I understand what you really want to ask, then 'Yes'. This calls C::func:

    C c;
    B* p = &c;
    p->func();
    


Examples using pointers as well as reference.

  • Using pointer

    B *pB = new C();
    pB->func(); //calls C::func()
    
    A *pA = new C();
    pA->func(); //calls C::func()
    
  • Using reference. Note the last call: the most important call.

    C c;
    B & b = c;
    b.func(); //calls C::func() 
    
    //IMPORTANT - using reference!
    A & a = b;
    a.func(); //calls C::func(), not B::func()
    

Online Demo : http://ideone.com/fdpU7


It calls the function in the class that you're referring to. It works it's way up if it doesn't exist, however.

Try the following code:

#include <iostream>
using namespace std;

class A {
    public:
    virtual void func() { cout << "Hi from A!" << endl; }
};

class B : public A {
    public:
    void func()  { cout << "Hi from B!" << endl; }
};

class C : public B {
    public:
    void func()  { cout << "Hi from C!" << endl; }
};

int main() {
  B* b_object = new C;
  b_object->func();
  return 0;
}

Hope this helps

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜