Vinodh said:
aBaseObject = aDerivedObject;
aBaseObject.FunctionX(); // Base FunctionX() is called
Okay. By using these statements we can never get/accees "Derived" classes
functionality through "aBaseObject".
It's more "get" than "access". To understand correctly, picture
yourself the operator= for the Base class :
Base &Base:
perator=(const Base& b)
{
this.data1 = b.data1;
this.data2 = b.data2;
...
}
That function is called with
Base b1
Derived b2; // or any type derived from Base or Base itself
b1 = b2;
which becomes
b1.operator=(b2);
As you see, only the parts Base is aware of are copied. That's normal,
because what Base works on are Base's also. Base's cannot know about
its derived class. Therefore, when do A = B, with A and B being two
automatic objects, A gets the parts of its type from B, but slices the rest.
Then whats the purpose of allowing such assignment?
I cannot think of an exact purpose right now since, as you say, we
usually are very careful not to allow slicing in our programs.
Actually, as soon as class polymorphism comes into play, we use
references and pointers.
The thing is, C++ is a low-level enough language not to disallow such
constructs. The thinking behind that is that you may need that feature
one day and you won't be able to replicate it. Something like muliple
inheritance, which you can avoid most of the time. But when you need
it, you really need it.
I am not clear about the OOAD principle behind the above assignment.
I feel such things should be prevented.
C++ has not the habit of forbidding things which can make sense in some
context. Slicing is considered a logic error (if you don't want it of
course), not a language error.
Jonathan