#include
using namespace std;
class C1 {
public:
int a;
public:
C1(){
a = 2;
}
virtual int getA() {
return a;
}
int f(C1* c) {
return c->a + c->getA();
}
};
class C2 : public C1 {
public:
int a;
public:
C2(){
a = 3;
}
int getA() {
return a;
}
int f(C2* c) {
return c->a + c->getA();
}
};
int main() {
C1 *c1 = new C1();
C2 *c2 = new C2();
C1 *c3 = c2;
coutf(c1) endl;
coutf(c2) endl;
coutf(c3) endl;
// coutf(c1) endl;//wrong class c2 cannot accept base pointer
coutf(c2) endl;
// coutf(c3) endl;
coutf(c1) endl;
coutf(c2) endl;
coutf(c3) endl;
delete c1;
delete c2;
return 0;
}
The result is:
4
5//because c->a =2 static binding c->getA() virtual function using C2->getA() 3
5
6
4
5
5
without virtual function the result would be
4
4//static binding all point to Base var and func
4
6
4
4
4