1

I'm wondering if the following constructors are the same for C++:

class foo
{ 
public:
   foo(void){};
...
}

and

class foo
{
public:
   foo(void);
...
}

Do curly brackets matter for these two cases? Thanks much!

xxks-kkk
  • 1,743
  • 3
  • 21
  • 39

4 Answers4

6

They're not same. {} represents a regular function-body and makes the former function definition.

foo(void){}; // function definition
foo(void);   // function declaration
songyuanyao
  • 147,421
  • 15
  • 261
  • 354
6

Yes they do. The second one will generate undefined reference to foo::foo (unless defined in another place). If you can use C++11 or above, you can use

foo()=default;

to define a compiler generated constructor

Tas
  • 6,589
  • 3
  • 31
  • 47
user877329
  • 5,419
  • 7
  • 34
  • 73
  • Thanks for the `=default` suggestion! – xxks-kkk May 21 '16 at 06:41
  • 1
    Note that `foo()=default;` is not exactly the same as `foo(){}`. The first is a "trivial" constructor, the second is not. User defined constructors are never trivial even if they are empty. – Jesper Juhl May 21 '16 at 08:27
3

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than the constructor would not already implicitly do.

In the second case, without them, the compiler will expect an implementation elsewhere - such as a .cpp file.

Niall
  • 28,102
  • 9
  • 90
  • 124
2

Yes. Without it is just a declarations. With both it is a declaration and definition. Try using it - you will get a linker error without the definition

Ed Heal
  • 55,822
  • 16
  • 77
  • 115