Douglas Edward
Douglas Edward

Reputation: 155

Cannot overload the >> operator with istream c++

I am trying to overload the >> operator to use it like cin with my class. Here is the code:

class Base {
public:
    int mx;
    Base() {}
    Base(int x) : mx(x) {}
    friend std::istream &operator>>(std::istream &, Base &);
    friend std::ostream &operator<<(std::ostream &, const Base &);

};

std::istream &operator >>(std::istream &in, Base &object) {
    in >> object.mx;
    return in;
}

std::ostream &operator <<(std::ostream &out, const Base &object) {
    out << object.mx;
    return out;
}

int main() {

    Base test();
    std::cin >> test;
    std::cout << test;
    system("PAUSE");


    return 0;

}

When I try to compile I get "error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'Base (__cdecl *)(void)' (or there is no acceptable conversion)" and Intellisense says no operator '>>' matches these operands.

the ostream version doesn't seem to have any problem.

Why?

Upvotes: 2

Views: 630

Answers (2)

nishant pathak
nishant pathak

Reputation: 359

the way you are creating the object is wrong , should use as : Base test;

Upvotes: 1

Daniel Frey
Daniel Frey

Reputation: 56921

Your code has two problems.

1) This declares a function instead of defining variable:

Base test();

Make that:

Base test;

2) You need to take a reference for the second parameter of operator>>:

std::istream &operator >>(std::istream &in, Base& object)

Also, your code does not really work for operator<<, at least it won't do what you are expecting it to do unless you fix problem 1) from above.

Upvotes: 3

Related Questions