-2

It looks like Coord(a) doesn't work , and the values for lon and lat are 00.0000 and 00.0000, those from the default constructor . What should I do? Ia there a problem with the syntax ? Isn't it in >> Coord(a) to read lon and lat from 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 is : "; in >> temp.lon;
    cout << "Latitude is  : "; 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 is : "; in >> a.model;
    cout << "Time is : "; in >> a.time;
    cout << "Speed is : "; in >> a.speed;
    cout << "Coordinates : " << endl; in >> Coord(a);
    return in;
}
};
void main()
{
   Location loc;
   cin>>loc; cout<<loc;
}
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
Mihai
  • 101
  • 2
  • 2
  • 8

1 Answers1

0

As I said, Coord(a) creates a copy (much like object slicing). Your code shouldn't compile, because you're passing an rvalue to operator>>, which takes an lvalue reference.

You have to use static_cast, to get a reference to the Coord base class:

in >> static_cast<Coord&>(a);

That will make it call the right operator>>.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
  • It works. Thank you very much ! But could you explain me in detail ? Does it create temporary lon and lat ? – Mihai Jan 15 '16 at 22:04
  • @Mihai And what's with the `00.000000000000`? Isn't `0` enough? `double` is not `std::string`, it's going to be truncated anyway. – LogicStuff Jan 15 '16 at 22:18
  • Yes , you are right . Just to remember how many digits the lon and lat have , because I use setprecision() during my program . – Mihai Jan 15 '16 at 22:33