Slicing in C ++, where am I mistaken?

I read about the slicing issue in C ++, and I tried a few examples (I'm from the Java background). Unfortunately, I do not understand some of these behaviors. I am currently stuck in this example (alternating example from Efficent C ++ Third Edition). Can someone help me figure this out?

My simple parent class:

class Parent
{
public:

    Parent(int type) { _type = type; }

    virtual std::string getName() { return "Parent"; }

    int getType() { return _type; }

private:

    int _type;
};

My simple child class:

class Child : public Parent
{

public:

    Child(void) : Parent(2) {};

    virtual std::string getName() { return "Child"; }
    std::string extraString() { return "Child extra string"; }
};

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);
}

Before the execution that I get:

Name: parent

Name: parent

Optional: extra line for children

Name after actor: Parent

, "". , . , . , p c, ( printNames ).

, "Name after cast: Parent", "Name after cast: Child"?

+4
2

- . Im :

Name: Parent
Name: Parent
Extra: Child extra string
bash: line 8:  6391 Segmentation fault      (core dumped) ./a.out

:

c printNames, . , , Parent, :

Parent(Parent const& other) : _type{other._type} {}

, _type c . Parent ( , Parent), c printNames.

p Child&. , p Child , ++ ( , , ).

undefined, . , Child::extraString this ( , ), . , , ( !).

, Child::getName, , , this ( ). , UB . "", . .

+8

. :

  • printNames(c) slices c, p Parent, c, p Parent.

  • Parent c, p 2, if

  • Child & c = static_cast<Child&>(p); " ( ), , p Child, ", p - Parent, Child c

    • theus , , , , .
  • c.extraString() ( ) , , c - Child ( , c.extraString virtual), , undefined Parent, , , , extraString , Child "ok"

  • c.getName() virtual, , Parent, ( ) Parent::getName

    • - , , undefined ++ ..
+2

All Articles