1

Reading through The C++ Programming Language, 4th Edition, there's a class defined like so

class Vector
{
    private:
        int sz;
        double *a;
    public:
        Vector(int s) :elem{new double[s]}, sz{s} {}
}

I'm a bit confused on how this constructor syntax works. I believe Vector(int s) is creating a constructor function that takes one parameter s, and that it initializes elem and sz. But why is there a :? I thought functions bodies were surrounded by {}? And so what do the empty braces {} at the end serve?

dav
  • 626
  • 4
  • 21

3 Answers3

5

: is called an initialiser list, which is used to quickly and concisely set values for the member variables when the constructor is called.

{} is the constructor's method body. Since the constructor is similar to a method, there has to be a body present for the code to compile. Since there is no need for any code in there, an empty body is used so the function does nothing.

DingusKhan
  • 123
  • 1
  • 15
  • 1
    Also the initialiser list happens before anything in the constructor body of the constructor gets executed – Philipp Nov 07 '17 at 12:32
  • 1
    Makes sense, thanks! I must've missed it reading through. I'll accept your answer once the cool down runs out. – dav Nov 07 '17 at 12:32
  • Is the initializer list unique to constructor functions only? For example, can I use it for a regular function? – dav Nov 07 '17 at 13:08
  • No, initialiser lists are only available on class constructors. – DingusKhan Nov 07 '17 at 13:09
2

This is initialization with Initializer List.

Alex
  • 9,891
  • 11
  • 53
  • 87
1

: is used to "initialize" the members of a class (this method is also called member initialization list)

there is a major difference between using : and function body {}

initiallizer list : initialize the members of class, whereas ,constructor body {} assigns the value to the members of the class.

the difference may not seem very big but it is actually the only way to initialize the const data type and reference data type members (which can only be initialized during declaration )

So when you do this

class Test
{
const int i; const string str;
public:
Test(int x, string y):i{x},str{y};
}

This would work, but if you try to assign values to const int i and const string str by writing their code in the body of constructor, it would lead to a result

And so what do the empty braces {} at the end serve?

nothing it is just compulsory to put those braces (even if it is empty)

They can basically serve as a function when you create an object of the class inside the main function and pass it the required arguments.

aditya rawat
  • 154
  • 10