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.