I have a doubt, the function below can receive an object of type A or something derived type.
A *copyToHeap(A &obj) {
A *ptr=new A(obj);
return ptr;
}
If we call it like this:
//B inherits from A
B bObj;
B *hPtr=copyToHeap(bObj);
The object pointed by hPtr is actually of type A or B?
Is safe doing this?
when you do the below in your code:
you’ll always get an A instance. obj will be treated as an A and a new A will get created based on the “A part” of obj.
The better approach is as an earlier reply indicated, add a virtual MakeCopy method to the base class and implement it for the derived classes.
This method is implemented by making a copy of the object for which its called. It then gets implemented in the derived classes so if you have an A pointer which is actually a B object you’ll get a true B copy and avoid the “slicing” which is occurring in your example.