danijar
danijar

Reputation: 34185

How to implement the extraction operator in a class?

I have a class that reads parts of a binary file into variables of different types.

class Foo {
public:
    size_t getSizeT();
    float getFloat();
    std::string getString();
private:
    std::ifstream stream;
};

Now I'd like to implement the stream extraction operator as described in this answer.

class Foo {
public:
    Foo &operator>>(Foo &foo, size_t &value);
    Foo &operator>>(Foo &foo, float &value);
    Foo &operator>>(Foo &foo, std::string &value);
private:
    std::ifstream stream;
};

The code fails to compile with this error message: error C2804: binary 'operator >>' has too many parameters. How to properly override the stream extraction operator? It should distinguish between types and be chainable.

Upvotes: 2

Views: 271

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409206

If an instance of your class is the source of the data, then you have two ways of writing the input operator function: Either as a stand-alone global function taking two arguments, the instance of your class and the destination object. Or you write it as a member-function of your class, and then it takes only a single argument which is the destination.

So for a global function you write e.g.

class Foo { ... };

Foo& operator>>(Foo& foo, int& i)
{
    // Get an integer and writes to `i` here
    return foo;
}

For a member function you write e.g.

class Foo
{
public:
    ...

    Foo& operator>>(int& i)
    {
        // Get an integer and writes to `i` here
        return *this;
    }
};

The reason I think you wrote the operator wrong, is because you can write the first version, using global functions, as friend function inline inside a class, and you have seen that before mistaking between the difference between a friend function and a member function.

You use friend functions like

class Foo
{
public:
    ...

    // Notice the keyword `friend` 
    friend Foo& operator>>(Foo& foo, int& i)
    {
        // Get an integer and writes to `i` here
        return foo;
    }
};

The difference between a member function and a friend function is subtle but very important.

Upvotes: 2

Jarod42
Jarod42

Reputation: 217468

As free function, operator signature should be:

Foo& operator >>(Foo& foo, size_t& value);

As member function (your case), it should be:

Foo& operator >>(size_t& value);

Upvotes: 3

Related Questions