Search code examples
c++constructorexecution

Why doesn't "foo f();" call the constructor of a class "foo"?


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

I bumped into the following problem. I created 2 instances of foo. Then I realized, that foo f(); didn't execute the contructor of a class. Why is that?

class foo{
public:
    foo() {cout <<"executed contructor...";}
};

int main() {
    foo f(); // doesn't run the ctor???? why?
    foo f2; // this one does execute the ctor


    system("pause");
    return 0;
}

Solution

  • The first declares a function. Try to access the object named f. The compiler will complain along the lines: f has non class type foo (), which means it is a function taking no arguments and returning an object of type foo.