i have 3 clases:
a{ abstract class }
b inherits a
c inherits a
i need create class d contains vector<a*> vect
in objects of both class b , c stored. idea create classa pointers , assign them address of classb , c objects. gathered called upcasting?
however, classa attributes stored in vector, inherited attributes aren't.
here's class contains vector:
class d{ vector<a*> vect; public: magazinvirtual& operator+=(a* obj){ vect.push_back(obj); return *this; } friend ostream& operator<<(ostream& out, d &obj){ vector<a*>::iterator it; (it = obj.vect.begin(); != obj.vect.begin(); ++it) out << **it << endl; return out; } };
class variables:
class a{ static int cod; char* denumire; int garantie; float pret; int stoc; };
class b:
class b:public a{ char* os; bool tipecran; float diagonala; };
class c:
class c:public a{ int tipaccesoriu;
here's how add objects vector: (don't shoot me horrible names , chained constructor calls, it's oop class , reason want exact same calls in main();
int main(){ b t1, t2("nokia 231", 2, 27, 10, "and", 1, 4); //t1 = t2; c a1("husa eh-17", 1, 2, 100, 0), a2("card sd64", 1, 10, 100, 2), a3 = a2; d dvect; *ptr1 = &t1; *ptr2 = &a1; += ptr1; += ptr2; cout << a; return 0; }
when using overloaded ostream operator class, despite fact there should 2 elements in vector(1b 1c), prints out classa attributes of first pushed object, classb object. in case, prints out:
nokia 231 / 2 / 27 / 10
here's ostream operators class b:
friend ostream& operator<<(ostream &out, b&obj){ out << (a&)obj << obj.os << endl <<obj.tipecran <<endl<<obj.diagonala<<endl; return out; }
and class c:
friend ostream& operator<<(ostream &out, c &obj){ out << (a&)obj << obj.tipaccesoriu << endl; return out; }
sorry long post , if seems dumb question, pointers genuinely make head spin. thank time!
run time polymorphism occurs through virtual functions of base class. operator<<
methods neither virtual nor members of base class.
the usual solution define ostream& operator<<(ostream &out, a&obj)
a
, not b
or c
inside function don't implement directly. instead have pass ostream&
parameter virtual function of class. such (inside a):
friend ostream& operator<<(ostream &out, a&obj){ return a.serialize( out ); } virtual ostream& serialize(ostream &out) { ... };
then later declare , define:
ostream& b::serialize(ostream &out){ a::serialize(out) << os << endl <<tipecran <<endl<<diagonala<<endl; return out; }
Comments
Post a Comment