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();
- Your code is invalid C++. What are the parentheses in class definition?
- It depends on the dynamic type of the object that is pointed to by
pointer_to_b_type
. 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
精彩评论