Search code examples
c++constructormost-vexing-parse

Why is the constructor not called when () is used to declare an object?


Possible Duplicate:
Why is it an error to use an empty set of brackets to call a constructor with no arguments?

$ cat cons.cpp
#include <iostream>

class Matrix {
private:
    int m_count;

public:
    Matrix() {
        m_count = 1;
        std::cout << "yahoo!" << std::endl;
    }
};

int main() {
    std::cout << "before" << std::endl;
    Matrix m1();                         // <----
    std::cout << "after" << std::endl;
}
$ g++ cons.cpp
$ ./a.out
before
after
$

What does the syntax Matrix m1(); do?

I believed that it is the same as Matrix m1;. Obviously I am wrong.


Solution

  • Matrix m1(); // m1 is a function whose return type is Matrix.
    

    Also this C++ FAQ lite entry should be helpful.

    Is there any difference between List x; and List x();