Saturday, August 25, 2007

upcast

#include
using namespace std;

class A{
protected:
virtual void print() { cout << "A" << endl; }
void print2() { cout << "AA" << endl; } // how about adding virtual?
};

class B {
public:
virtual void print() { cout << "B" << endl; }
void print2() { cout << "BB" << endl; }
};

class C : public A, public B{
public:
void print2() { cout << "CC" << endl; }
};

int main() {
C c;
B* p = &c;
p->print2();
}

Answer: BB
if using 'virtual', then answer is CC

When assigned the address of the object to base class, the new defined function in derived class will be un-accessible to that pointer. If a function is defined 'virtual' in base class and is overrided it in derived class, the copy in derived class will be called. Otherwise, the copy in base class is called.

No comments:

Post a Comment