object-slicing

Store derived class objects in base class variables

回眸只為那壹抹淺笑 提交于 2019-11-26 00:54:02
问题 I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible. Imagine this program: #include <iostream> #include <vector> using namespace std; class Base { public: virtual void identify () { cout << \"BASE\" << endl; } }; class Derived: public Base { public: virtual void identify () { cout << \"DERIVED\" << endl; } }; int main () { Derived derived; vector<Base> vect; vect.push_back(derived); vect[0].identify();

What is object slicing?

≯℡__Kan透↙ 提交于 2019-11-25 21:30:04
问题 Someone mentioned it in the IRC as the slicing problem. 回答1: "Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away. For example, class A { int foo; }; class B : public A { int bar; }; So an object of type B has two data members, foo and bar . Then if you were to write this: B b; A a = b; Then the information in b about member bar is lost in a . 回答2: Most answers here fail to explain what

Store derived class objects in base class variables

做~自己de王妃 提交于 2019-11-25 19:10:33
I would like to store instances of several classes in a vector. Since all classes inherit from the same base class this should be possible. Imagine this program: #include <iostream> #include <vector> using namespace std; class Base { public: virtual void identify () { cout << "BASE" << endl; } }; class Derived: public Base { public: virtual void identify () { cout << "DERIVED" << endl; } }; int main () { Derived derived; vector<Base> vect; vect.push_back(derived); vect[0].identify(); return 0; } I expected it to print "DERIVED", because the "identify" method is virtual. Instead 'vect[0]' seems