I know we can cast a derived class to a base class using pointers
so if A is a base class and B is a derived class
B *b = new B();
A *a = (A*)b;
Can that also be done if the variable is not pointer ?
I tried doing it and it didn't work. so i assumed it cannot be done. IT makes sense because I don't have a constructor which takes in B and spits out A. But i have come to read a couple of code lines which indicates otherwise .
Generally... derived classes contain the parent class and additional info. Therefore you can't cast between them because they are different size and have different details.
What you can do, though, is create a new A based on an existing B. For example:
1 2
B b;
A a = b;
This will work, however note that:
1) a and b will be two separate objects. So it's not a cast, it's a copy.
2) a will have lost some information from b. Only the 'A' portion of b will have been copied. Things specific to B will have been lost.
If I cast from B to A, should it not just truncate till all the information of A and B are consistent ?
I mean if i try to do the same for double and int, thats what happens rite !!
It seems thats exactly what is happening for the code you have written. just casting is not being allowed !! is my interpretation correct ??