Search code examples
c++constructorcopy-constructordefault-constructor

(Simple Constructor Concept) Why doesn't Foo(); do anything?


This is a simple C++ constructor concept I'm having trouble with.

Given this code snippet:

#include <iostream>
using namespace std;

class Foo 
{
public:
    Foo ()      {       cout << "Foo()"  << endl;     }
    ~Foo ()     {       cout << "~Foo()" << endl;     }
};

int main()
{
    Foo f1;
    Foo f2();
}

The output was:

Foo()
~Foo()

It seems like Foo f2(); doesn't do anything. What is Foo f2(); And why doesn't it do anything?


Solution

  • Foo f2(); declares a function named f2 which takes no argument and returns an object of type Foo

    Also consider a case when you also have a copy constructor inside Foo

    Foo (const Foo& obj)     
    {     
         cout << "Copy c-tor Foo()"  << endl;    
    } 
    

    If you try writing Foo obj(Foo()), in this case you are likely to expect a call to the copy c-tor which would not be correct.

    In that case obj would be parsed as a function returning a Foo object and taking an argument of type pointer to function. This is also known as Most Vexing Parse.

    As mentioned in one of the comments Foo obj((Foo())); would make the compiler parse it as an expression (i.e interpret it as an object) and not a function because of the extra ().