0

If I have a base class that I declared it as a child class, and then added to a vector consisting of the base class, is there a way to cast that base class back to a child class, since I know that the "base" is in fact the child? For example:

class Libitem{
    //......
};

class Book : public Libitem{
    //......
}

int main{
    vector<Libitem> lib;
    Libitem book = Book();
    lib.push_back(book);
    Book b = static_cast<Book>(lib.at(0)); //this is wrong. Is there a way to do this correctly?
}

Am I doing my cast wrong or is their something that I'm misunderstanding?

Steven Zhao
  • 301
  • 1
  • 2
  • 8
  • 1
    You are victim of object slicing. [What is object slicing?](http://stackoverflow.com/questions/274626/what-is-object-slicing) To get polymorphic behaviour you will need to use pointers or references. Also read up on [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast) – user4581301 Apr 13 '17 at 14:45
  • "since I know that the "base" is in fact the child?" thats not correct. The base is the child minus all fields that the child adds to the base – 463035818_is_not_an_ai Apr 13 '17 at 14:48

0 Answers0