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?
Foo f2();declares a function namedf2which takes no argument and returns an object of typeFooAlso consider a case when you also have a copy constructor inside
FooIf 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
objwould 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().