0
#include <iostream>
using namespace std;

struct Foo{
    Foo(){}
    Foo(int){}
    void fun(){}
};

void main()
{
    Foo a(10);
    a.fun();
    Foo b();
    b.fun();//error
    Foo c = Foo(); // this is the right way to use default constructor?
    c.fun();
}

The code has an error when compiling, because b is not a type of class, who can tell me what is b? And the meaning of Foo b()?

Niall
  • 30,036
  • 10
  • 99
  • 142
zawdd
  • 311
  • 1
  • 3
  • 12

2 Answers2

1

This problem is commonly known as C++ "most vexing parse".

Foo b();

This declares a function named b returning Foo.

It should be just;

Foo b;

This will declare a variable b of type Foo that will be default initialised (Foo has a default constructor). Foo c = Foo(); yes, this is an alternative default initialisation (copy initialisation) but it is generally used more with POD data types.

It is worth noting that with C++11 (uniform initialisation), the following will compile and is possibly an alternative for you

Foo b{};

But it does the same thing in this case (with respect to constructing b).

Community
  • 1
  • 1
Niall
  • 30,036
  • 10
  • 99
  • 142
  • This is vexing, but doesn't quite qualify as *most vexing*. – T.C. Aug 29 '14 at 08:45
  • @T.C., :), Scott did write that around 2001, so in the 13 or so years since, things may have got worse... – Niall Aug 29 '14 at 08:49
  • `std::vector v(std::istream_iterator(ifs), std::istream_iterator());` is the standard "most vexing" example :) – T.C. Aug 29 '14 at 08:51
0

The right way should be:

Foo b;

You just declared a function named b.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405