c++ - mistake in vector showing -
this question has answer here:
- what object slicing? 15 answers
i have 2 simple classes. want vector show result, number not showed. on other hand, when try result without vector, result show. can me? thank you.
#include <iostream> #include <string> #include <vector> #include <iterator> using namespace std; template<typename t> class 1 { protected: t word; t word2; public: one() {word = "0"; word2 = "0";} one(t w, t w2) {word = w; word2 = w2;} virtual const void show() {cout << word << endl; cout << word2 << endl;} }; template<typename t> class 2 : public one<t> { private: int number; public: two() {number = 0;} two(t w, t w2, int n) : one(w,w2) {number = n;} virtual const void show () {cout << word << endl; cout << word2 << endl; cout << number << endl; } }; int main () { one<string> *idk; two<string> *something = new two<string>("asd","aa",1); idk = something; idk->show(); // ok - asd, aa, 1 vector<one<string>> arr; arr.push_back(*idk); arr.at(0).show(); // wrong - asd,aa return 0; }
you storing one<string>
instances instead pointers them one<string>*
.
since object stored totally in vector cell, there no polymorphism object suffers slicing: additional feature inherits one
in instance placing inside vector discarded.
try vector<one<string>*>
pointer stored , problem doesn't occur. mind that, manage memory, using smart pointer when working stl collections wise choice.
Comments
Post a Comment