Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Overloading operator << for child classes

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.

like image 973
PetrS Avatar asked Dec 14 '22 23:12

PetrS


1 Answers

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.

like image 57
Alex Shtof Avatar answered Jan 03 '23 14:01

Alex Shtof