// A1.cpp - return pointers to bases. // Can you prove the results are correct? #include using namespace std; class A { public: virtual ~A() { } virtual void mf() { cout << "\n A::mf()"; } private: int i; }; class B { public: virtual ~B() { } virtual void mf() { cout << "\n B::mf()"; } private: double d; }; class C : public A, public B { public: A* pointerToA() { return static_cast(this); } B* pointerToB() { return static_cast(this); } void anotherpA(A *&pA) { pA = (A*)this; } void anotherpB(B *&pB) { pB = (B*)this; } }; void main() { C c; A* pA = c.pointerToA(); pA->mf(); B* pB = c.pointerToB(); pB->mf(); //////////////////////////////////////////////////////////// // proof: // addresses of a and b objects lie on or inside c object, // as shown below cout << "\n address of c object is: " << &c << ", size of c object is: " << sizeof(c); cout << "\n address of a object is: " << pA << ", size of a object is: " << sizeof(A); cout << "\n address of b object is: " << pB << ", size of b object is: " << sizeof(B); c.anotherpA(pA); c.anotherpB(pB); cout << "\n address of a object is: " << pA; cout << "\n address of b object is: " << pB; cout << "\n\n"; }