Inheritance



1
2
3
4
5
6
7
8
9
10
  class Base
{
public:
    int m_nValue;
 
    Base(int nValue=0)
        : m_nValue(nValue)
    {
    }
}

is it the same as
1
2
3
4
5
6
7
8
9
10
11
  class Base
{
public:
    int m_nValue;
 
    Base(int nValue)
    {
         nValue=0;
         m_nValue=nValue;
    }
}

No, not quite. Before we go on, there is NO inheritance here (the colon operator is being used for something different).'

In the first example, on line 6, the int nValue=0 specifies a default argument, i.e. that argument is optional, and if not specified, this is the value it retrieves. For example, you can construct as any one of these:
1
2
Base a(); // m_nValue = 0
Base b(10); // m_nValue = 10 


The colon on line 7 specifies an initializer list - it specifies to call the constructor of the specified object with the specified parameters. Its normally used because it is often faster and more efficient than doing it in the body of the constructor, and sometimes you need to use it (for example, giving parameters to the constructor of a base class).

In your second example, what ever nValue is you will always set m_nValue to 0. Apart from that and what may be a slight efficiency decrease (though that may be optimized out), it is exactly the same.
Last edited on
The only way to have a private member reference or const would be using the initializer list. Anyways your code for the second example would mean that m_nValue is always 0. So you might as well just do
1
2
3
4
Base()
{
    m_nValue = 0;
}
Just like the other answers, I see two differences:

First optional parameters:
Base(int nValue=0)
versus
Base(int nValue)

The first one takes an optional first parameter in the constructor. If you don't use a parameter in your constructor, it'll be 0. The second one must take a value (though another issue in that second constructor is that you over-write that input with a 0, leaving that input unused.

Second, initializer list:
1
2
Base(int nValue=0)
    : m_nValue(nValue)

The code above says that m_nValue is created and initialized to nValue.
1
2
3
Base(int nValue){
     m_nValue=nValue;
}

The code above says that m_nValue is created, and is later set to nValue.

For primative types, this isn't very interesting, but it can be very interesting otherwise for these reasons:
1. You can specify a non-default constructor for a member in your initializer list.
2. You can skip a potentially lengthy default constructor for a member in your initializer list.
3. You can initialize a const member in your initializer list.

Last edited on
Topic archived. No new replies allowed.