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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With