1

I'm declaring an instance of a class like so:

Matrix m;

This appears to implicitly initialize m (i.e. run the constructor). Is this actually the case?

OregonGhost
  • 23,359
  • 7
  • 71
  • 108

3 Answers3

8

Yes, the default constructor is called.

If there is no default constructor, this statement is ill-formed. If there are no user-declared constructors, the compiler provides a default constructor.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
0

Yes, it creates an instance of class Matrix on the stack. This instance is intialized using the default constructor of class Matrix. This instance created on stack will be destroyed when the variable m goes out of scope. When the object is destroyed its destructor will be called.

Naveen
  • 74,600
  • 47
  • 176
  • 233
-2

Yes, syntactically this is equal to writing:

Matrix m();

Although, if there is no default constructor defined the compiler will give an error.

NOTE: If no constructors are defined for a class a default constructor is made by the compiler, but if a constructor with parameters is defined the default constructor is NOT made by the compiler.

J Higs
  • 114
  • 5
  • 10
    It is not syntactically equal to writing that. That declares a function named `m` that takes no parameters and returns a `Matrix`. – James McNellis Apr 21 '10 at 16:18
  • 2
    You might see this question about this topic: http://stackoverflow.com/questions/2318650/is-no-parentheses-on-a-c-constructor-with-no-arguments-a-language-standard – James McNellis Apr 21 '10 at 16:28
  • My mistake. When using 'new' you can choose to add the '()' or not. – J Higs Apr 21 '10 at 16:41