Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ostream << operator not getting invoked

I have created a class Animal with some basic properties and added a no data constructor.
I have overloaded the ostream operator as well to print the properties.

Animal.cpp

#include<bits/stdc++.h> 
using namespace std;

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, Animal &animal) {
        return animal.write(os);
    }
};



int main() {
    cout << "Animal: " << Animal() << "\n";
}

However I am getting error in the main that invalid operands to binary expression ostream and Animal.
It works fine if I declare Animal and then call the cout. But how to make it work like this (initialize and cout at the same time) ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The 2nd parameter of operator<< is declared as Animal &; Animal() is a temporary and can’t be bound to lvalue-reference to non-const.

You can change the type to const Animal &; temporary could be bound to lvalue-reference to const. (Then write needs to marked as const too.)

class Animal {
    string name;
    int action;
public: 
    Animal() {
        name = "dog";
        action = 1;
    }
    ostream& write(ostream& os) const {
        os << name << "\n" << action << "\n";
        return os;
    }
    friend ostream& operator<<(ostream& os, const Animal &animal) {
        return animal.write(os);
    }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading