Reputation: 1110
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.
Upvotes: 4
Views: 2002
Reputation: 170074
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;
}
Upvotes: 4
Reputation: 2640
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.
Upvotes: 8