Overloading operator<< for a nested private class possible?
Asked Answered
D

2

17

How one can overload an operator<< for a nested private class like this one?

class outer {
  private:
    class nested {
       friend ostream& operator<<(ostream& os, const nested& a);
    };
  // ...
};

When trying outside of outer class compiler complains about privacy:

error: ‘class outer::nested’ is private
Dab answered 10/11, 2011 at 15:44 Comment(0)
S
17

You could make the operator<< a friend of outer as well. Or you could implement it completely inline in nested, e.g.:

class Outer
{
    class Inner
    {
        friend std::ostream& 
        operator<<( std::ostream& dest, Inner const& obj )
        {
            obj.print( dest );
            return dest;
        }
        //  ...
        //  don't forget to define print (which needn't be inline)
    };
    //  ...
};
Square answered 10/11, 2011 at 15:49 Comment(4)
and the print function should be a const member function. If it is std::ostream& print(std::ostream &out) const, then operator<< can be just one line : return obj.print(dest);.Senhorita
Why does std:ostream need to be a friend of Inner?Echt
Because you can't define it in Inner otherwise. (And if it's not defined in Inner, you have the problem that it can't access Inner, because Inner is a private member of Outer.)Square
@Echt - It's basically an inline free-function (i.e. not a member function) definition inside a class. The thing that's a friend isn't std::ostream, it's operator<<( std::ostream& dest, Inner const& obj ). The std::ostream & is just the return type of the function.Anglo
P
10

if you want the same thing in two different file (hh, cpp) you have to friend two time the function as follow:

hh:

// file.hh
class Outer
{
    class Inner
    {
        friend std::ostream& operator<<( std::ostream& dest, Inner const& obj );
        // ...
    };

    friend std::ostream& operator<<( std::ostream& dest, Outer::Inner const& obj );
    //  ...
};

cpp:

// file.cpp:
#include "file.hh"

std::ostream    &operator<<( std::ostream& dest, Outer::Inner const& obj )
{
    return dest;
}
Partee answered 15/11, 2014 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.