I read about the slicing problem in C++ and I tried some examples (I am from Java background). Unfortunatelly, I do not understand some of the behaviour. Currently, I am stucked in this example (alternated example from Efficent C++ Third Edition). Can anybody help me to understand it?
My simple class of a parent:
class Parent
{
public:
Parent(int type) { _type = type; }
virtual std::string getName() { return "Parent"; }
int getType() { return _type; }
private:
int _type;
};
My simple class of a Child:
class Child : public Parent
{
public:
Child(void) : Parent(2) {};
virtual std::string getName() { return "Child"; }
std::string extraString() { return "Child extra string"; }
};
The main:
void printNames(Parent p)
{
std::cout << "Name: " << p.getName() << std::endl;
if (p.getType() == 2)
{
Child & c = static_cast<Child&>(p);
std::cout << "Extra: " << c.extraString() << std::endl;
std::cout << "Name after cast: " << c.getName() << std::endl;
}
}
int main()
{
Parent p(1);
Child c;
printNames(p);
printNames(c);
}
Afte the execution I get:
Name: Parent
Name: Parent
Extra: Child extra string
Name after cast: Parent
I understand the first two lines, because it is the cause of the "slicing". But I do not understand why can I cast the child into parent via the static cast. In the book, there is written that after the slicing, all the specialized information will be sliced off. So I suppose, I cannot cast p into c, because I do not have infomation (in the beginning of the function printNames a new Parent object is created without the additional information).
Additionaly, why I am getting the "Name after cast: Parent" if the cast was successful instead of "Name after cast: Child"?