oop - C++ Vector of Subclasses, using it to overload the istream/ostream -
i'm looking hold vector of objects, of subclasses.
i thought able declaring vector of pointers baseclass (such vector<baseclass*> db
), , declare subclass doing db.pushback(new subclass)
(my example in link below touch different, along same lines);
is possible store multiple subclasses in sense or need define new vector each subclass? in example given, there 1, realistically in program there four.
if so, in overloaded >> in subclass1, dynamic casting type baseclass work call friended overloaded >> in baseclass?
edit:
sorry, wasn't entirely clear in second half of question. should have expanded.
i have program needs take input, , distribute throughout respective classes , subclasses. should take input cin >> class;
, in case have overloaded >> operator.
however, when define data subclass (lines 34 39, , line 44), appears call baseclass, rather subclass. calls friend function defined in baseclass @ line 10, rather in line 21.
i'm not sure going wrong.
ideally output should be
printing:data x = 1 y = 2
you should have virtual fromserial function reads in necessary data each class. here example http://ideone.com/wgwj8l . notice user of virtual keyword. need polymorphism. , note virtual destructor well.
#include <iostream> #include <vector> using namespace std; class baseclass{ public: int x; public: baseclass(){x = 0;} virtual istream& fromserial(istream& stream){ return stream >> x; } virtual void print(){ cout << "baseclass::x = " << x << endl; } virtual ~baseclass(){} }; class subclass1: public baseclass{ public: int y; public: subclass1(){y = 0;} virtual istream& fromserial(istream& stream){ baseclass::fromserial(stream); //read baseclass first return stream >> y; } virtual void print(){ baseclass::print(); cout << "subclass1::y = " << y << endl; } }; baseclass* createnewclass(baseclass * temp) { cout << "input 2 values: "; temp->fromserial(cin); return temp; } int main() { vector<baseclass*> db; db.push_back(createnewclass(new subclass1)); cout << "\nprinting data: " << endl; db[0]->print(); }
input: 1 2
output:
input 2 values: printing data: baseclass::x = 1 subclass1::y = 2
Comments
Post a Comment