基类的指针或引用会根据运行时绑定的对象,动态的选择是执行基类的虚函数还是派生类的虚函数。对于非虚函数的成员访问,比如调用非虚成员函数,或访问成员属性,只能访问指针或引用所指定的静态类型(这里指基类)的非虚成员,而不管动态类型是什么。
也就是说多态是针对虚函数来说的。
以下是测试代码:
//test for dynamic_cast
#include <iostream>
using namespace std;
class Base {
public:
string name = "parent";
virtual void who() {
cout << "i am parent." << endl;
}
void p() {
cout << "parent" << endl;
}
};
class Child : public Base {
public:
string name = "child";
void who() override {
cout << "i am son." << endl;
}
void c() {
cout << "child" << endl;
}
};
int main(void) {
//test pointer
{
Base* pb = new Base();
Child* pc = new Child();
auto p = dynamic_cast<Base*> (pc);
p -> who(); //child
p -> Base::who(); //parent.
cout << p -> name << endl; //parent
cout << dynamic_cast<Child*> (p) -> name << endl; //child
p -> p(); //parent
//p -> c(); //error, no member named c()
dynamic_cast<Child*> (p) -> p();
dynamic_cast<Child*> (p) -> c();
cout << endl;
delete pb, pc;
}
//test reference
{
cout << endl << "test ref" << endl;
Child child;
Base &ref = child;
//virtual func
ref.who(); // son
ref.Base::who(); //parent
//general member data
cout << ref.name << endl; //parent
cout << dynamic_cast<Child&> (ref).name << endl; //child
//general member function
ref.p();
//ref.c(); //error, no member c()
dynamic_cast<Child&> (ref).c();
dynamic_cast<Child&> (ref).p(); //correct
}
}