HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

C++, What does the colon after a constructor mean?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
constructorcolonthedoesmeanafterwhat

Problem

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?

Solution

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

  • Calling base class constructors



  • 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.

Code Snippets

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

Context

Stack Overflow Q#2785612, score: 449

Revisions (0)

No revisions yet.