JKop wrote:
Karl Heinz Buchegger posted:
Sree wrote:
If class B derives from class A and we create an array of class B like
B *arrayOfB = new B[10]; and
// Instance of A
A firstInstanceOfA;
How can we store firstInstanceOfA in arrayOfB ?
You can't.
A 'B' object is an 'A' object also. But the reverse is not
true: an 'A' object is not a 'B' object.
I tried the following way
arrayOfB[0] = firstInstanceOfA;
arrayOfB[0] = (B*)firstInstanceOfA;
Both the ways doesn't seems to work, also if we need to reverse the
way of assigning, like
A *arrayOfA = new A[10];
and we need to store instance of B what has to be done ?
You can't either.
a 'B' object extends an 'A' object. So if you assign a 'B'
object to an A variable ...
B ObjB;
A[0] = ObjB;
... the 'A-part' of B is extracted and stored in the variable.
We say: the B object has been sliced to an A object (it looses
all its B information, until just an A object is left)
Well just in case you already knew that:
A a_object;
arrayOfB[0] = static_cast<B*>(&a_object);
That's the equivalent of telling the compiler:
"Dear compiler. I know that those types don't fit. But
listen closely: I don't care. You better do what I tell
you to do, or I will switch of the power immdiatly"
And then the compiler has no other choice: He silently
does what you request it to do, even if it is plain wrong.
That's the culprit with casts. They are a way to simply
shut down the compiler and overrule everything. A cast
is a weapon. It has to be used wisely.
--
Karl Heinz Buchegger
kb******@gascad.at