Bloomberg LP Interview Question
/*
class A{//..};
class B1:public A{//..};
class B2:public A{//..};
how to cast A part of B1 to A part of B2
*/
# include <iostream>
using namespace std;
class A
{
//int &i;
public:
int x;
virtual ~A(){};
};
class B1: public A
{
public:
int y;
};
class B2:public A
{
public:
int y;
};
int main()
{
B1 *objB1 = new B1();
B2 *objB2 = new B2();
objB1->x = 10;
objB1->y = 15;
objB2->x = 20;
objB2->y = 16;
cout<<"objB1->x="<<objB1->x<<endl;
cout<<"objB1->y="<<objB1->y<<endl;
cout<<"objB2->x="<<objB2->x<<endl;
cout<<"objB2->y="<<objB2->y<<endl;
cout<<"using no cast "<<endl;
objB2->x = ((A *)objB1)->x;
cout<<"After cast"<<endl;
cout<<"objB1->x="<<objB1->x<<endl;
cout<<"objB1->y="<<objB1->y<<endl;
cout<<"objB2->x="<<objB2->x<<endl;
cout<<"objB2->y="<<objB2->y<<endl;
objB1->x = 10;
objB1->y = 15;
objB2->x = 20;
objB2->y = 16;
cout<<" resetting "<<endl;
//cout<<"objB1->x="<<objB1->x<<endl;
//cout<<"objB1->y="<<objB1->y<<endl;
//cout<<"objB2->x="<<objB2->x<<endl;
//cout<<"objB2->y="<<objB2->y<<endl;
cout<<"using reinterpret_cast "<<endl;
objB2->x = reinterpret_cast<B2 *>(objB1)->x;
cout<<"After cast"<<endl;
cout<<"objB1->x="<<objB1->x<<endl;
cout<<"objB1->y="<<objB1->y<<endl;
cout<<"objB2->x="<<objB2->x<<endl;
cout<<"objB2->y="<<objB2->y<<endl;
objB1->x = 10;
objB1->y = 15;
objB2->x = 20;
objB2->y = 16;
cout<<" resetting "<<endl;
//cout<<"objB1->x="<<objB1->x<<endl;
//cout<<"objB1->y="<<objB1->y<<endl;
//cout<<"objB2->x="<<objB2->x<<endl;
//cout<<"objB2->y="<<objB2->y<<endl;
A *p1 = objB1;
A *p2 = objB2;
p2->x = p1->x;
objB2 = dynamic_cast<B2*>(p1);
objB2 = dynamic_cast<B2*>(p2);
cout<<"using dynamic_cast "<<endl;
cout<<"After cast"<<endl;
cout<<"objB1->x="<<objB1->x<<endl;
cout<<"objB1->y="<<objB1->y<<endl;
cout<<"objB2->x="<<objB2->x<<endl;
cout<<"objB2->y="<<objB2->y<<endl;
return 0;
}
I would consider application of 'reinterpret_cast' or 'dynamic_cast' C++ operators, something like ( it is used in MFC widely! ):
...
A *a = new A();;
B1 *b1 = reinterpret_cast< B1 * >( a );
B2 *b2 = reinterpret_cast< B2 * >( a );
or
B1 *b1 = dynamic_cast< B1 * >( a );
B2 *b2 = dynamic_cast< B2 * >( a );
...
Take into account, that when 'dynamic_cast' can't cast a pointer of some type to a pointer of another type it will return NULL! Also, in terms of Late Runtime Binding it has to be done in a different way:
...
A *a1 = ( A * )new B1();
A *a2 = ( A * )new B2();
...
and in all classes destructors are need to be declared as 'virtual'.
- Sourav Sain January 02, 2011