1

I'm a bit newbie in c++ but why this code prints that the queue item is not a child while I created him as a child:

class Parent
{
public: virtual const char* getName() { return "Who is your daddy?"; }
};

class Child : public Parent
{
public: virtual const char* getName() { return "La gente esta muy loca?"; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    std::deque<Parent> queue;   
    queue.push_back(Child());
    Parent* p = &queue.back();
    if (dynamic_cast<Child*>(p) == 0) { std::cout << "I am not child"; }
    else { std::cout << "Welcome, son"; }
    std::cin >> c;
    return 0;
}
Mikhail Ivanov
  • 113
  • 2
  • 3
  • 10
  • 7
    http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – juanchopanza Sep 26 '14 at 20:43
  • 1
    The deque stores `Parent` instances, *not* pointers or references to them. You don't get polymorphism in C++ without pointers or references, all you did was *convert* your `Child` to a `Parent` instance when you pushed it to the deque, so when you go fetch a pointer to it, it truly is a `Parent`. – cdhowie Sep 26 '14 at 20:47
  • The `deque` holds `Parent` objects so when you push a `Child` on it, it 'forgets' it really holds a `Child` and stores it as a `Parent` instead. The cast can't know that happened, so you get "I am not a child". If you store `Parent*` instead, it should function correctly – edtheprogrammerguy Sep 26 '14 at 20:48
  • Okay, I understand what is slicing, but i don't understand now what should i do to get my child object from queue back? And more over, I don't understand for what dynamic_cast is needed if I can't call child methods anyway – Mikhail Ivanov Sep 26 '14 at 20:50
  • @MikhailIvanov - you have to store pointers instead so the polymorphism will work correctly. – edtheprogrammerguy Sep 26 '14 at 20:51
  • @MikhailIvanov You use `dynamic_cast` with pointer or reference types, never with actual object types. – cdhowie Sep 26 '14 at 20:53

0 Answers0