Search code examples
c++oopoverloadingostream

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) ?


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);
        }
    };