shinzou
shinzou

Reputation: 6192

C++ constructor syntax and zero-initialization

This is a short question about syntax in c++:

class arrayInit {
 public:
  bool vars[2];

  arrayInit() : vars() {} //1
};

class array {
 public:
  bool vars[2];
  array() {} //2
};

What does 1 and 2 do?

Why they don't zero initialize like this: bool vars[2]={};?

What is the purpose of arrayInit() : and array()? and what is it called so I could search for it?

It's from: https://msujaws.wordpress.com/2010/06/16/initializing-an-array-in-c/

Upvotes: 1

Views: 1002

Answers (3)

Mido
Mido

Reputation: 665

Both arrayInit() and array() are default constructors. If the default constructor is missing and other constructors are available, you cannot declare an object from that class type without calling the other constructors e.g. you cannot do this arrayInit arr; without the default constructor.

The part : vars() is called the initialization list. You can read more about them in this link: http://en.cppreference.com/w/cpp/language/initializer_list

Upvotes: 1

bashrc
bashrc

Reputation: 4835

What does 1 and 2 do?

Both 1 and 2 define the default constructor for the respective type

Why they don't zero initialize like this: bool vars[2]={};?

They could if they were using a compiler with c++11 support. Also var() will value initialize the array which is same as vars[2] = {} will explicitly initialize all elements to false

What is the purpose of arrayInit() : and array()? and what is it called so I could search for it?

They are called the default constructors. C++ compiler will create them for you unless you want to do something special in them. If you were mentioning about what is written beyond the : (colon), that expression is called the initializer list

Read more here

Upvotes: 5

Russell Elfenbein
Russell Elfenbein

Reputation: 551

What does 1 and 2 do?

Both allow you to override the default initialization for an array. InitArray is specifically initializing the vars array with no parameters, I believe it will assume 0 as the default parameter. Array is not specifically initializing the array, so it is falling back to a default initialization case.

Why they don't zero initialize like this: bool vars[2]={};?

You could do this, this is just another option which encapsulates the bool array in a class to allow you to provide other functionality if you wish.

What is the purpose of arrayInit() : and array()?

If you want default functionality, there is no need to encapsulate the array in its own class. Encapsulation allows you to encapsulate a type to provide different functionality from the default, you could go on to add methods for addition, subtraction, or anything you can think up and have it perform the methods in the way that you specify.

and what is it called so I could search for it?

Good question; Encapsulation, class initialization, array initialization.

http://www.cplusplus.com/doc/tutorial/classes/
    

Upvotes: 2

Related Questions