Question

From my understanding of declarations and definitions, at the global scope:

MyClass instance();//Declares a function that returns a MyClass
MyClass instance;//Declares an instance of MyClass

Is it possible to declare a variable and define it to use the default constructor at global scope? What if I was using a structure instead of a class?

EDIT:

Okay, so MyClass instance; does call the default constructor. Can anyone explain how this is consistent with this example:

int a; // not default constructed, will have random data 
int b = int(); // will be initialised to zero
Was it helpful?

Solution

MyClass instance;

will invoke the default constructor (i.e. the constructor with no parameters).

This is counter-intuitive, because to invoke an overloaded constructor with parameters you would do the following:

MyClass instance(param1, param2);

Logic would tell you that you pass in an empty argument list to invoke the default constructor, but the following code...

MyClass instance();

...looks like a prototype to the compiler rather than the construction of a MyClass object.

There is no difference between a struct and a class in C++, except that a struct has public members by default and a class has private members by default.

OTHER TIPS

  1. It doesn't matter whether you're at global scope or not.
  2. MyClass instance; is a definition (using the default constructor, not just a declaration. To get only a declaration (e.g. in a header file), you would use extern MyClass instance;.
  3. It doesn't matter, for this part, whether MyClass is a class or a struct. The only thing that changes between structs and classes in C++ is the default interpretation of whether members and bases are public or private.
  4. If you want to be explicit, you could write MyClass instance = MyClass();.
MyClass instance;

is also a definition, using the default constructor. If you want to merely declare it you need

extern MyClass instance;

which is not a definition. Both, however, have external linkage.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top