Default constructor (created automatically)

There are 3 steps in creating an object of class.

  1. Distributing memory space for the object
  2. Initializing member variables using initializer
  3. Running constructor — our topic

An object is created after a call to constructor. In other words, the constructor must be called to create an object (instance).  To prevent the case programmer does not create a constructor, the c++ compiler automatically creates “default constructor”.

* Default constructor does not have any parameters, it does not return anything. It is not void though.

If you create a class that looks like this:

Snip20150502_13 Notice there isn’t a constructor. Then, c++ compiler automatically creates a default constructor. So the above example is same as,

Snip20150502_14

One way to efficiently initialize member variables: Member Intializer

// By the way, this is my first post ever! xD I am very excited!

Member initializer can be used to initialize member variables in class. Actually, there are two possible ways to initialize member variables.

1. Initializing in constructor’s body

Snip20150502_7

2. Initializing using member initializer

Snip20150502_4

num1(n1) has same meaning as num1 = n1.

Both work, but many c++ programmer prefer member initializer because there two benefits in it:

1. Member initializer clearly shows what object is initialized

2. Efficiency.

Member variables that are initialized with initializer is more efficient because initializer declares and initializes at the same time. For example, num1(n1) is same as int num1 = n1; In the contrary, initializing at constructor’s body (num1 = n1) is same as

int num1;

num1 = n1;

To summarize, using initializer creates binary code that declares and initialize at once. Initializing at constructor’s body creates binary code that will declare and initialize member variables separately at different lines.

Which means… we can initialize const variables using initialize! Remember? const variables have to be declared & initialized at the same time.

Here is the example:

Snip20150502_10

See? Convenient!