Using ostream overloading on pointers to objects - c++

So, I have a struct Bike, which looks like this
struct Bike {
std::string brand;
std::string model;
bool is_reserved;
friend std::ostream& operator<<(std::ostream out, const Bike& b);
};
std::ostream& operator<<(std::ostream out, const Bike& b) {
return out
<< "| Brand: " << b.brand << '\n'
<< "| Model: " << b.model << '\n';
}
And another class BikeRentalService, which has a std::vector<Bike*> called bikes_m. This class also has a method print_available_bikes(), which is supposed to iterate over said std::vector<Bike*> and print each Bike by using the overloaded operator<< shown above. This method looks like that:
void BikeRentalService::print_available_bikes(std::ostream& out) {
if (bikes_m.empty()) {
out << "| None" << '\n';
}
else {
for (auto bike : bikes_m) {
if (!bike->is_reserved) {
out << bike;
}
}
}
}
The problem is that using this function just prints out the addresses of those Bike objects. Dereferencing the objects before using out << does not work either, Visual Studio says it can't reference std::basic_ostream because it is a "deleted function".
Writing the for loop as (auto *bike : bikes_m) does not change anything.

The rigth way to overload the ostream operator is as follows:
struct Bike {
std::string brand;
std::string model;
bool is_reserved;
friend std::ostream& operator<<(std::ostream& out, const Bike& b); // <- note passing out by reference
};
std::ostream& operator<<(std::ostream& out, const Bike& b) {
return out
<< "| Brand: " << b.brand << '\n'
<< "| Model: " << b.model << '\n';
}
Also, as noted by #KyleKnoepfel you should change out << bike; to out << *bike; too.

Related

Why my overloaded operator is not working for derived class

I was trying to learn operator overloading in C++ PL. I made an exercise shown below. What I want to do is overload << operator for each derived class and use it on my main. But whenever I do it, its only working for Base class. What is the problem here?
Class Employee:
class Employee {
public:
string name;
int id;
int exp_level;
double salary;
Employee() {
this->name = "";
this->id = 0;
this->exp_level = 0;
this->salary = 0.0;
}
~Employee() {
//WTF
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Employee& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << endl;
return os;
}
};
Class Technical:
class Technical : public Employee {
public:
string profession;
Technical() {
this->profession = "";
}
~Technical() {
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Technical& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << "Technical" << endl;
return os;
}
};
Class Engineer:
class Engineer : public Employee {
public:
Engineer() {
}
~Engineer() {
}
virtual void calculateSalary() {
//CODE
}
virtual void registerX() {
//CODE
}
friend ostream& operator<<(ostream& os, const Engineer& e) {
os << e.name << " " << e.exp_level << " " << e.id << " " << e.salary << "Engineer" << endl;
return os;
}
};
Main Method:
int main()
{
Employee* e = new Employee();
Employee* t = new Technical();
Employee* ee = new Engineer();
cout << *e << endl;
cout << *t << endl;
cout << *ee << endl;
}
Output:
0 0 0
0 0 0
0 0 0
C++ chooses the best overload based on the static type's of the function arguments, and because the type is Employee in this case, the Employee's operator<< gets called.
If you want it to call the correct version when you have a static type pointer / reference to it that doesn't match it's dynamic type you'll have to use a virtual function or use dynamic_casts / typeid to check for the concrete runtime type (virtual functions are the cleanest approach imho)
Example: godbolt
class Employee {
public:
virtual ~Employee() = default;
friend std::ostream& operator<<(std::ostream& os, const Employee& e) {
return e.put(os);
}
protected:
virtual std::ostream& put(std::ostream& os) const {
os << "Employee!";
return os;
}
};
class Technical : public Employee {
protected:
std::ostream& put(std::ostream& os) const override {
os << "Technical Employee!";
return os;
}
};
class Engineer : public Employee {
protected:
std::ostream& put(std::ostream& os) const override {
os << "Engineer Employee!";
return os;
}
};
int main() {
Employee* e = new Employee();
Employee* t = new Technical();
Employee* ee = new Engineer();
std::cout << *e << std::endl;
std::cout << *t << std::endl;
std::cout << *ee << std::endl;
delete ee;
delete t;
delete e;
}
would result in:
Employee!
Technical Employee!
Engineer Employee!
Also keep in mind that once you have at least 1 virtual function in a class then the destructor should almost definitely be also virtual.
e.g.:
Employee* e = new Technical();
delete e;
would only call ~Employee(), but not ~Technical(), if the destructor is not virtual.
So whenever you want to delete an object through a pointer to one of it's base-classes the destructor needs to be virtual, otherwise it's undefined behavior.
Due to these declarations
Employee* e = new Employee();
Employee* t = new Technical();
Employee* ee = new Engineer();
the static type of the expressions *e, *t, *ee is Employee &. So the operator
friend ostream& operator<<(ostream& os, const Employee& e)
is called for all three objects.
A simple way to make the friend operator << "virtual" is to define in each class a virtual function like for example
virtual std::ostream & out( std::ostream & ) const;
and define the (only) friend operator like
friend ostream& operator<<(ostream& os, const Employee& e)
{
return e.out( os );
}
The virtual function out need to be redefined in each derived class.

C++ insertion operator for class method

In C++ is there a way to use the insertion operator for a class method?
This operator<< overload is working:
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
Complex() {};
~Complex() {};
};
I can do this:
int main()
{
Complex* o = new Complex();
std::cout << "This is test: " << *o << "." << std::endl; // => This is test: test overload.
}
I know about stream manipulators, like this:
std::ostream& welcome(std::ostream& out)
{
int data = 1;
out << "WELCOME " << data << "\r\n";
return out;
}
int main()
{
std::cout << "Hello " << welcome; // => "Hello WELCOME 1\r\n"
}
How can I put the welcome method into the Complex class and then how shall I call it from cout (please note that welcome method must access some class member variables)?
My trial:
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
std::ostream& welcome(std::ostream& out) {
out << "WELCOME " << data << "\r\n";
return out;
}
Complex() { data = 1; };
~Complex() {};
private:
int data;
};
int main()
{
Complex* o = new Complex();
std::cout << "This is test2: " << o->welcome << std::endl; // compile error
}
One easy way to pick a different << overload is to use a different type.
#include <iostream>
class Complex {
public:
//Normal overload:
friend std::ostream& operator<<(std::ostream &out, const Complex &o) {
out << "test overload";
return out;
}
struct extra_info {
const Complex& parent;
extra_info(const Complex& p) : parent(p) {}
friend std::ostream& operator<<(std::ostream& out, const extra_info& ei){
int i = 1;
out << "extrainfo " << i;
return out;
}
};
extra_info extrainfo() {
return {*this};
}
Complex() {};
~Complex() {};
};
int main() {
Complex c;
std::cout << c << "\n";
std::cout << c.extrainfo();
}
Output:
test overload
extrainfo 1
I suppose in your real code you are using members. Hence the helper type must hold a reference to the Complex instance.

No match for operator << in exception handling program

#include <iostream>
#include <string>
#include "NegativeBalanceException.hpp"
#include <memory>
class Account
{
private:
std::string name;
double balance;
public:
Account(std::string name, double balance);
~Account() {std::cout <<"Calling Account Destroyer" << std::endl;}
void get_name() const {std::cout << name << std::endl;}
void get_balance() const {std::cout << balance << std::endl;}
friend std::ostream &operator<<(std::ostream &os, const Account &account);
};
Account::Account(std::string name, double balance)
: name{name}, balance{balance} {
if (balance < 0)
throw NegativeBalanceException();
}
std::ostream &operator<<(std::ostream &os, const Account &account) {
os << "Account Name: " << account.get_name() << "\n" << "Account
Balance: " << account.get_balance() << std::endl;
return os;
}
int main () {
std::unique_ptr<Account> Austin;
try {
Austin = std::make_unique<Account>("Austin",1000);
std::cout << *Austin << std::endl;
}
catch (const NegativeBalanceException &ex) {
std::cerr << ex.what() << std::endl;
}
};
Hello I am a beginner programmer and I am practicing exception handling and I do not know why my overloaded operator << is not working. It won't let me display my data that I want.
Your get_name() and get_balance() methods are both declared with void return values, so your overloaded operator<< can't pass them to os << .... Internally, the methods are doing their own logging to std::cout, so you would need to change your operator<< accordingly, eg:
std::ostream &operator<<(std::ostream &os, const Account &account) {
os << "Account Name: ";
account.get_name();
os << "Account Balance: ";
account.get_balance();
return os;
}
However, this will not work as expected if os does not refer to std::cout, for example if your main() decided to stream the Account to a std::ofstream instead.
A better option is to change get_name() and get_balance() to return values instead, and not do their own logging directly:
std::string get_name() const { return name; }
double get_balance() const { return balance; }
Then your overloaded operator<< will work as expected.
These
void get_name() const {std::cout << name << std::endl;}
void get_balance() const {std::cout << balance << std::endl;}
should be written like this
std::string get_name() const { return name; }
double get_balance() const { return balance; }
Functions which return values are not the same as functions which print values. In your overloaded operator<< you need two functions to return the values in the account object, so the operator<< can print them.

Overloading operator <<

class Vehicle
{
public:
//[...]
virtual std::ostream& ostreamOutput(std::ostream&) const; // virtual in order to use it for subclasse like cars, busses etc.
virtual double Speed() const; //returns the speed of a vehicle, is implemented in derived classes
private:
int Number
std::string Name
//[...]
protected:
int MaxSpeed; //these variables were also needed in the derived classes
};
std::ostream& Vehicle::ostreamOutput(std::ostream& os) const
{
os << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left) << std::setfill(' ') << ""
<< std::setw(4) << Number
<< std::setw(9) << Name
<< std::setw(15) << Speed()
<< std::setw(5) << MaxSpeed
return os;
}
std::ostream& operator<<(std::ostream& os, const Vehicle& x)
{
x.ostreamOutput(os);
return os;
}
main() //I wanted to overload the "<<"-Operator in order to print the vehicle information without //a seperate function
{
Vehicle Vehicle1("Vehicle1", 80);
std::cout << Vehicle1 << std::endl;//the first shift-operator contains the error
}
I tried to overload the Shiftoperator but I get the error named:
"error c2679 binary ' ' no operator found which takes a right-hand operand of type".
The error occured in the first Shift Operator in the main function. I want to print Vehicle and its derived classes with the overloaded operator.
Can you explain the error to me? I really do not know how to correct this.
I fixed all the typos (missed semicolons) in your source, and here is a complete working example:
#include <iostream>
#include <iomanip>
using namespace std;
class Vehicle
{
public:
//[...]
Vehicle (const char* Name, int Number)
: Name (Name), Number (Number)
{}
virtual std::ostream& ostreamOutput(std::ostream&) const; // virtual in order to use it for subclasse like cars, busses etc.
virtual double Speed() const {return 0.;} //returns the speed of a vehicle, is implemented in derived classes
private:
// remove in-class initializers below if you need to avoid C++11
int Number = -1;
std::string Name = "not set";
//[...]
protected:
int MaxSpeed = 200; //these variables were also needed in the derived classes
};
std::ostream& Vehicle::ostreamOutput(std::ostream& os) const
{
os << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left) << std::setfill(' ') << ""
<< std::setw(4) << Number
<< std::setw(9) << Name
<< std::setw(15) << Speed()
<< std::setw(5) << MaxSpeed;
return os;
}
std::ostream& operator<<(std::ostream& os, const Vehicle& x)
{
x.ostreamOutput(os);
return os;
}
int main() //I wanted to overload the "<<"-Operator in order to print the vehicle information without //a seperate function
{
Vehicle Vehicle1("Vehicle1", 80);
std::cout << Vehicle1 << std::endl;//the first shift-operator contains the error
}
Maybe you output some other variables for which operator<< is not defined. To debug this case, split the code from e.g. this:
os << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left) << std::setfill(' ') << ""
<< std::setw(4) << Number
<< std::setw(9) << Name
<< std::setw(15) << Speed()
<< std::setw(5) << MaxSpeed;
to this:
os << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left) << std::setfill(' ') << ""
<< std::setw(4) << Number;
os << std::setw(9) << Name;
os << std::setw(15) << Speed();
os << std::setw(5) << MaxSpeed;
This way you'll get the error message for the real line that is causing trouble. Otherwise you'll get the error message only for the first line, the compiler you use apparently does not distinguish the lines in this case.
Your code example contains only typos (Vehicle <-> Fahrzeug, ostreamAusgabe <-> ostreamOutput, semicolon after Speed() in ostreamOutput()). Overloaded operator<< should work fine.
Try to compile and launch this code:
class Vehicle
{
public:
Vehicle(const std::string& name, int num)
: Name(Name)
, Number(num)
, MaxSpeed(100)
{}
virtual std::ostream& ostreamOutput(std::ostream&) const;
virtual double Speed() const;
private:
int Number;
std::string Name;
protected:
int MaxSpeed;
};
double Vehicle::Speed() const
{
return 0.0;
}
std::ostream& Vehicle::ostreamOutput(std::ostream& os) const
{
os << std::resetiosflags(std::ios::right) << std::setiosflags(std::ios::left) << std::setfill(' ') << ""
<< std::setw(4) << Number
<< std::setw(9) << Name
<< std::setw(15) << Speed()
<< std::setw(5) << MaxSpeed;
return os;
}
std::ostream& operator<<(std::ostream& os, const Vehicle& x)
{
x.ostreamOutput(os);
return os;
}
int main()
{
Vehicle Vehicle1("Vehicle1", 80);
std::cout << Vehicle1 << std::endl;
return 0;
}

C++ ostream << Operator

I have a Class that deals with Music Albums. The artists and albums are strings. It also has a collection (vector) of tracks called contents. Each track has a title and a duration.
This is my ostream <<:
ostream& operator<<(ostream& ostr, const Album& a){
ostr << "Album: " << a.getAlbumTitle() << ", ";
ostr << "Artist: " << a.getArtistName() << ", ";
ostr << "Contents: " << a.getContents() << ". "; //error thrown here
return ostr;
}
The << next to the a.getContents() is underlined and says: "Error: no operator "<<" matches these operands.
What am I missing out or doing wrong? Can you not use vectors in this way? or maybe its something I'm missing from my Track class?
Assuming Album::getContents() returns std::vector<Track>, you need to provide
std::ostream& operator<<(std::ostream& o, const Track& t);
and
std::ostream& operator<<(std::ostream& o, const std::vector<Track>& v);
where the latter can use the former. For example:
struct Track
{
int duration;
std::string title;
};
std::ostream& operator<<(std::ostream& o, const Track& t)
{
return o <<"Track[ " << t.title << ", " << t.duration << "]";
}
std::ostream& operator<<(std::ostream& o, const std::vector<Track>& v)
{
for (const auto& t : v) {
o << t << " ";
}
return o;
}
There's a C++03 demo here.
If Album::getContents() is about your vector and you just return the vector than ostream does not know how to write it, because there is no '<<' operator.
Just overload the '<<' operator for a vector and you are happy.