Andrew Brockert
Andrew Brockert

Reputation: 113

C++ constructor behavior

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?

Upvotes: 1

Views: 241

Answers (3)

Naveen
Naveen

Reputation: 73433

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.

Upvotes: 0

J Higs
J Higs

Reputation: 114

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.

Upvotes: -2

James McNellis
James McNellis

Reputation: 354979

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.

Upvotes: 8

Related Questions