-3

How should I get rid of the problem with object slicing in c++.

In my application if the derived class has some dynamically allocated pointer and derived class object is assigned to base class object, the behavior is memory corruption!

iammilind
  • 68,093
  • 33
  • 169
  • 336
srinuvenu
  • 475
  • 1
  • 5
  • 11
  • 4
    This is easily the worst-presented question I have seen in a long time. Voting to close on principle. – Moo-Juice Jul 28 '11 at 12:23
  • Actually this is the reason of bad design..Your design definitely do not follow the OOP principal.. Define the pointer in the base class.. Never change the functionality. – Bhupesh Pant Sep 30 '13 at 17:46

2 Answers2

1

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.

iammilind
  • 68,093
  • 33
  • 169
  • 336
0

you can't. you should solve the problem with the pointer. if you want to assign Obj2 to Obj1, override assign operator (operator=)

cprogrammer
  • 5,503
  • 3
  • 36
  • 56