开发者

how to over come the issue of object slicing in c++ [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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=)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜