Question

I have created a class Location which is a parent class for classes Village and City. I have a vector<Location*>, which contains villages and cities. Now, I need to print to the standard output the content of this vector. This is easy:

    for (int i = 0; i < locations.size(); i++)
       cout << locations.at(i);

I have overloaded operator << for classes Village, City and Location. It is called overloaded operator << from class Location all the time. I need to call overloaded operator for Village and City (depends on specific instance). Is there something similar like virtual methods for overloading operators?

I'm new in programming in C++, I'm programming in Java, so please help me. Thanks in advance.

Was it helpful?

Solution

Short answer

No, there is no such thing. You can use existing C++ features to emulate it.

Long answer

You can add a method to Location virtual void Print(ostream& os) and implement operator<< like this:

std::ostream& operator<<(ostream& os, const Location& loc) 
{ 
    loc.Print(os); 
    return os; 
}

If you override Print() in your derived classes you will get your desired functionality.

OTHER TIPS

Since operator<< can't be a member function (without changing its semantics), you could provide a virtual print method and do double dispatch..

class Location
{
  virtual void print (ostream&);
}

ostream& operator << (ostream& o, Location& l)
{
  l.print(o); // virtual call
  return o;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top