3

The error looks like this (2nd last line):

Error: no match for 'operator>>' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()')|

Here is the code:

#include <iostream>

using namespace std;

class Complex {
  private:
    int a, b;
  public:
    Complex(int x, int y) {
        a = x;
        b = y;
    }
    Complex() {
        a = 0;
        b = 0;
    }
    friend ostream& operator << (ostream &dout, Complex &a);
    friend istream& operator >> (istream &din, Complex &a);
};

ostream& operator << (ostream &dout, Complex &a) {
    dout << a.a << " + i" << a.b;
    return (dout);
}

istream& operator >> (istream &din, Complex &b) {
    din >> b.a >> b.b;
    return (din);
}

int main() {
    Complex a();
    cin >> a;
    cout << a;
}

1 Answer 1

6
Complex a();

This is a vexing parse. You think it means "default-initialize the variable a, which has type Complex." However, the compiler parses it as "declare a function called a which takes no arguments and returns a Complex value." The syntax is ambiguous: it could mean either, but the language prefers a function declaration to a variable declaration.

Therefore, a is a function, not a variable.

Indeed, there is no declared operator overload that takes a function, which is why you get the error. Note the specific type called out in the error:

operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'Complex()'
                                                   parens indicate a function ^^

To fix this, replace this line with one of these:

Complex a{}; // C++11 and later only; uniform initialization syntax
Complex a;   // All versions of C++

Neither of these are ambiguous; they can only be parsed as a variable declaration.

Sign up to request clarification or add additional context in comments.

8 Comments

But i have made constructors for the same purpose. Why is it that it is giving error while passing nothing to constructor.
… or auto a = Complex(); — there are a lot of arguments in its favour; foremost that, if used consistently, it completely removes the most vexing parse from consideration.
@OmkarArora Read the link. The declaration is a function declaration, not an object declaration.
@KonradRudolph One could make the same argument about uniform initialization. It also removes the most vexing parse from consideration by the use of curly braces.
@OmkarArora The problem is the declaration of a in int main(). This has nothing to do with the definition of Complex::Complex().
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.