Anybody knows how to convert object of one class to object of another class using type conversion? i read in a c++ book simply assign it like this obj1=obj2 where both are objects of different classes..but its not working..plz tell ..thanks in advance :)

Showing Answers 1 - 3 of 3 Answers

rizi

  • Oct 30th, 2006
 

You cannot try a conversion objects of two different classes by simple assignment. You can do either of overloading the assignment operator or writing a conversion routine in your source object. The code for the latter can be as follows:class A{private: int aa;public: A(){aa=0;}};class B{private: int bb;public: B(int y){bb=y;}operator A(){ int aa = bb/2;}};void main(){A a1,a2;B b1(20);B b2(30);a1=b1;a2=b2;}after the assigment statements in main() a1.aa will be 10 and a2.aa will be 15. Hope this helps..Alternatively if you do not have access to source class code you can write a similar routine in destination class as well

Madhurgeek

  • May 28th, 2007
 

This can be done through pointers like A *a1 and B *b1 ok. Then you have to assigh some value  to *a1 and *b1 but remember with the use valueat sign(*). Now your task is to convert the object of A class to B or vice-versa so you have to do only one thing that is typecasting of pointers like:

void main ()
{
A *a1; // a1 can only point to A type of objects only.
B *b1;
a1=(A*)b1; // now a1 can point to B type of object.
}

so firstly *a1 was object of A class but 5th statement a1 has become the object of B class.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions