307

Possible Duplicates:
Variables After the Colon in a Constructor
C++ constructor syntax question (noob)

I have some C++ code here:

class demo 
{
private:
    unsigned char len, *dat;

public:
    demo(unsigned char le = 5, unsigned char default) : len(le) 
    { 
        dat = new char[len];                                      
        for (int i = 0; i <= le; i++)                             
            dat[i] = default;
    }

    void ~demo(void) 
    {                                            
        delete [] *dat;                                           
    }
};

class newdemo : public demo 
{
private:
    int *dat1;

public:
    newdemo(void) : demo(0, 0)
    {
     *dat1 = 0;                                                   
     return 0;                                                    
    }
};

My question is, what are the : len(le) and : demo(0, 0) called?

Is it something to do with inheritance?

Amr
  • 411
  • 6
  • 21
bcoughlan
  • 25,987
  • 18
  • 90
  • 141
  • 8
    Duplicate of http://stackoverflow.com/questions/1272680/c-constructor-syntax-question-noob, http://stackoverflow.com/questions/2349978/variables-after-the-colon-in-a-constructor, http://stackoverflow.com/questions/2445330/importance-of-a-singlecolon-in-c, http://stackoverflow.com/questions/1632484/c-initialization-question – outis May 07 '10 at 01:39
  • 96
    **DO NOT DELETE** questions with good answers! [Jeff said so!](http://meta.stackexchange.com/questions/50069/why-are-we-deleting-instead-of-merging/50106#50106) – Konrad Rudolph May 31 '10 at 14:28
  • @KonradRudolph One of these duplicate questions was deleted, unfortunately: http://stackoverflow.com/questions/2445330/importance-of-a-singlecolon-in-c – Anderson Green Nov 29 '14 at 05:48
  • 1
    @Anderson Ah what a shame. I cast an undelete vote – but it needs three. :-( – Konrad Rudolph Nov 29 '14 at 10:56
  • @KonradRudolph Just FYI, [Jeff's merged question](https://stackoverflow.com/questions/43434/how-to-improve-problem-solving-skills) in that meta post was also deleted, so the community might have moved on since then. – jrh Oct 29 '18 at 19:08

6 Answers6

433

As others have said, it's a member initializer list. You can use it for two things:

  1. Calling base class constructors
  2. Initializing data members before the body of the constructor executes

For case #1, I assume you understand inheritance (if that's not the case, let me know in the comments). So you are simply calling the constructor of your base class.

For case #2, the question may be asked: "Why not just initialize it in the body of the constructor?" The importance of the member initializer lists is particularly evident for const members. For instance, take a look at this situation, where I want to initialize m_val based on the constructor parameter:

class Demo
{
    Demo(int& val) 
     {
         m_val = val;
     }
private:
    const int& m_val;
};

By the C++ specification, this is illegal. We cannot change the value of a const variable in the constructor, because it is marked as const. So you can use the initializer list:

class Demo
{
    Demo(int& val) : m_val(val)
     {
     }
private:
    const int& m_val;
};

That is the only time that you can change a const data member. And as Michael noted in the comments section, it is also the only way to initialize a reference that is a data member.

Outside of using it to initialize const data members, it seems to have been generally accepted as "the way" of initializing members, so it's clear to other programmers reading your code.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Smashery
  • 57,848
  • 30
  • 97
  • 128
  • 33
    To be clear - in addition to initializing `const` members, it's the only way to initialize reference members, whether `const` or not (since an assignment to a reference is an assignment to what the reference refers to). – Michael Burr May 07 '10 at 02:01
  • can we do something like this `Demo():m_val(NULL)` I am doing this but its giving me errors, any idea what i am doing wrong? – 2am Oct 14 '13 at 11:33
  • @Smashery : Regarding `That is the only time that you can change a const member variable : ` something like `*const_cast(&m_val)+=5;` may be used to override constness & volatility – sjsam Apr 14 '15 at 10:12
  • @Smashery **m_val = val;** in ctor is pointless even if **int& m_val** is not **const**. Your explanation would be clear if you'd not used references. – Roman Nov 23 '17 at 16:27
  • @MichaelBurr Burr extremely important comment – Roman Nov 23 '17 at 16:28
  • 1
    It would be useful to add the name of the feature number 2: the member initializer list. – user31389 Aug 12 '19 at 11:11
  • 1
    @Smashery that's not even more questionable than the confusing one : what'd be used in enclosure, bow or curly brace ? As often seen e.g: class Vector { Vector(int s) :elem{new double[s]}, sz{s} { } ... } –  Oct 09 '19 at 04:34
  • @MichaelBurr What's wrong with the constructor: `Demo(int &val) {m_val = val }` ? `val` can be passed to the constructor from outside to initialize a non-const `m_val`. – Xfce4 Jan 06 '22 at 22:39
  • I thought this was the first question to pop in everyone's heads, but I don't see it mentioned in the comments. `You can use it for two things: Calling base class constructors`. Why would I want to call base class constructor if it is already implicitly called when instantiating a variable of child class type? – M.Ionut Jun 24 '22 at 20:54
49

This is called an initialization list. It is for passing arguments to the constructor of a parent class. Here is a good link explaining it: Initialization Lists in C++

dbyrne
  • 59,111
  • 13
  • 86
  • 103
7

It's called an initialization list. It initializes members before the body of the constructor executes.

Chris Schmich
  • 29,128
  • 5
  • 77
  • 94
7

It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.

If you use = to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.

Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
  • Following code shows that your comment about = is wrong. Using initialization list, value will be set according to initialisation list. Using assignment: class cl { public: cl() { cout<<"before setting is "< – Padmanabha V Sep 16 '19 at 07:22
3

It means that len is not set using the default constructor. while the demo class is being constructed. For instance:

class Demo{
    int foo;
public:
    Demo(){ foo = 1;}
};

Would first place a value in foo before setting it to 1. It's slightly faster and more efficient.

wheaties
  • 35,646
  • 15
  • 94
  • 131
1

You are calling the constructor of its base class, demo.

Chris O
  • 5,017
  • 3
  • 35
  • 42