Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the C++ default constructor always called, as indicated in C++ Primer?

Tags:

c++

I'm newbie to C++. Don't mind this stupid question:

In C++ primer 4th edition (Stanley Lipmann) on page 52, there is a sentence which says:

The default constructor is used regardless of where a variable is defined.

Can anyone explain a bit more? This statements seem like it is missing something.

like image 991
extdummy Avatar asked Aug 24 '10 02:08

extdummy


1 Answers

From the book itself:

Each class may also define what happens if a variable of the type is defined but an initializer is not provided. A class does so by defining a special constructor, known as the default constructor. This constructor is called the default constructor because it is run "by default;" if there is no initializer, then this constructor is used. The default constructor is used regardless of where a variable is defined.

(my italics).

So you're in a section of the book where they're already talking about default constructors (as should be evident in some of the other answers, the default constructor is most definitely not always used).

All that the book is saying is, in those situations where the default constructor is used, it makes no difference at all where the variable is defined (inside or outside functions, inside or outside classes, inside braces such as loops, selection statements or even naked braces, and so on).

like image 75
paxdiablo Avatar answered Sep 29 '22 09:09

paxdiablo