how to over come the issue of object slicing in c++ [closed]
How should I get rid of the problem with object slicing in c++.
In my application if the der开发者_如何学Goived class
has some dynamically allocated pointer and derived class
object is assigned to base class
object, the behavior is memory corruption!
It depends on your design. You may have to change certain design criteria to get rid of it. One of the options is to have an overloaded operator =
and copy constructor in your base class
for particular derived class
.
class Derived;
class Base
{
//...
private:
Base (const Derived&);
Base& operator = (const Derived&); // private and unimplemented
};
Now if you attempt to do something like following:
Derived d;
Base b;
b = d; // compiler error
it will result in compiler error.
you can't. you should solve the problem with the pointer. if you want to assign Obj2 to Obj1, override assign operator (operator=)
精彩评论