2

I have two classes "Base" and "Derived". Derived inherits the Base class. Let Base has a variable named "i". And Derived has a variable "derived_i".

class Base
{
public:
  int i;
};

class Derived : public Base
{
public:
  int derived_i;
};

In the following code,

Base *a;
... // Some code operating on a.
// Now "a" points to an object of type "Derived". So,
cout << a->i; // Displays 2.
cout << ((Derived *)a)->derived_i; // Displays 3.

Base *b;

Now I have to assign the value of a to b and delete "a" without affecting b. I tried using a local temporary variable,

Base *b;
Base tmp = *a;
delete a;
b = new Base(tmp);
// But, narrowing occured and,
cout << b->i; // This prints 2.
cout << ((Derived *)b)->derived_i; // This did not print 3.

This implies that the Derived part didn't copy correctly and so the error occurs.

Fish
  • 1,205
  • 1
  • 10
  • 12
  • You'll find [this question and its top answers](http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c) rather informative. – WhozCraig Jul 13 '14 at 06:20

1 Answers1

1

In this line:

Base tmp = *a;

If *a is of type derived, it gets sliced down to Base. You could try this:

Base *b = new Derived(*a);
yizzlez
  • 8,757
  • 4
  • 29
  • 44