BigBerger
BigBerger

Reputation: 1803

C++ - ostream (<<) overloading

I was wondering if there is any way to overload the << operator for a class without declaring it as a friend function. My professor said this is the only way to do it, but I wanted to know if there is another way that he was unaware of.

Upvotes: 1

Views: 4017

Answers (5)

woodstok
woodstok

Reputation: 2784

As R Sahu has pointed out, the requirement is that the operator should be able to access everything it has to display.

Here are a few possible options

1.Adding the overloaded function as a friend function

2.Making all the required data members of the class accessible for the function using either public accessor methods or public data members

class MyClass {
   private:
   int a;
   int b;
   int c;
   public:
   MyClass(int x,int y,int z):a(x),b(y),c(z) {};
   MyClass():a(0),b(0),c(0) {};
   int geta() { return a; }
   int getb() { return b; }
   int getc() { return c; }
};

std::ostream& operator<<(std::ostream &ostr,MyClass &myclass) {
   ostr << myclass.geta()<<" - " << myclass.getb() << " - " << myclass.getc() ;
   return ostr;
}


int main (int argc, char const* argv[])
{
   MyClass A(4,5,6);
   cout << A <<endl;

        return 0;
}

3.Add a public helper function , say output with the signature std::ostream& output(std::ostream& str) and use it later in the operator function.

Upvotes: 0

deeiip
deeiip

Reputation: 3379

You need to declare it is as friend function if and only if you need access to it's private members.
You can always do this without using friend function if:
1) No private member access is required.
2) You provide a mechanism to access your private member otherwise. e.g.

class foo
{
    int myValue;
    public:
    int getValue()
    {
        return myValue;
    }
}

Upvotes: 2

Edward
Edward

Reputation: 7080

Yes, one way to do it is like this:

class Node
{
public:
    // other parts of the class here
    std::ostream& put(std::ostream& out) const { return out << n; };
private:
   int n;
};

std::ostream& operator<<(std::ostream& out, const Node& node) {
    return node.put(out);
}

Upvotes: 0

R Sahu
R Sahu

Reputation: 206567

There is no need to make the operator<< function a friend of the class as long as everything you want to be output is accessible through the public interface of the class.

Upvotes: 2

Cramer
Cramer

Reputation: 1795

Yes, you can

std::ostream& operator<<(std::ostream &stream, WHATEVER_TYPE var) {
    std::string str = somehowstringify(var);
    return stream << str;
}

Note however that by virtue of it being a non-member non-friend function it can of course only access the public interface of std::ostream, this usually isn't a problem.

Upvotes: 0

Related Questions