Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(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?

like image 725
Jason Avatar asked Dec 06 '11 05:12

Jason


2 Answers

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 ().

like image 123
Prasoon Saurav Avatar answered Nov 15 '22 11:11

Prasoon Saurav


You are actually declaring f2 as a function that takes no parameters and returns a Foo.

like image 40
Vaughn Cato Avatar answered Nov 15 '22 10:11

Vaughn Cato