c++ - Read an attribute of the base class using "istream" of derived class -
it looks coord(a)
doesn't work , , values lon
, lat
00.0000
, 00.0000
, default constructor . should do? ia there problem syntax ? isn't in >> coord(a)
read lon
, lat
base class?
//base class class coord { private: double lon; double lat; coord() { lon = 00.000000000000000; lat = 00.000000000000000; } //..... //..... //..... friend istream& operator>>(istream& in, coord& temp) { cout << "longitude : "; in >> temp.lon; cout << "latitude : "; in >> temp.lat; return in; } }; //derived class class location : public coord { private: char model[6]; double time; int speed; //..... //..... //..... friend istream& operator>>(istream& in, location& a) { cout << "model : "; in >> a.model; cout << "time : "; in >> a.time; cout << "speed : "; in >> a.speed; cout << "coordinates : " << endl; in >> coord(a); return in; } }; void main() { location loc; cin>>loc; cout<<loc; }
as said, coord(a)
creates copy (much object slicing). code shouldn't compile, because you're passing rvalue operator>>
, takes lvalue reference.
you have use static_cast
, reference coord
base class:
in >> static_cast<coord&>(a);
that make call right operator>>
.
Comments
Post a Comment