Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default constructor in C++

I was just curious about the question, but couldn't find the answer in the Internet.

Let's suppose we have simple header:

// SimpleHeader.h
class SimpleClass
  {
  int i;
  }

As we know, the default constructor is automatically generated for this class.

Now I have 2 more files:

// First.cpp
#include <SimpleHeader.h>
// ...
SimpleClass a;
// ...

and

//Second.cpp
#include <SimpleHeader.h>
// ...
SimpleClass b;
// ...

Will both First.obj and Second.obj contain code for the class

like image 655
Werolik Avatar asked Sep 08 '11 14:09

Werolik


People also ask

What is the use of default constructor?

The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.

What is a default constructor give an example?

Example 5: Default Constructor The default constructor initializes any uninitialized instance variables with default values. In the above program, the variables a and b are initialized with default value 0 and false respectively. The output of the program is the same as Example 5.

Why is it called a 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.


1 Answers

From the standard: If you do not write any constructors, a default constructor will be provided for you, and this default constructor is defined inline and equivalent to an empty constructor T::T() {}.

I'm pretty sure that [edit]your thus inlined constructor will not actually result in any machine code at all.

like image 184
Kerrek SB Avatar answered Sep 30 '22 15:09

Kerrek SB