Showing posts with label constructor. Show all posts
Showing posts with label constructor. Show all posts

Friday, February 19, 2016

C++ : constructor initialization list

In the implementation of the constructor, it is possible to initialize internal members with an initialization list. It is basically a list of parameters following a semicolon (:) with their initialization values :

Basic initialization


class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;

public:
    Something()
    {
        m_nValue = 0;
        m_dValue = 0.0;
        m_pnValue = 0;
    }
};


With an initialization list


class Something
{
private:
    int m_nValue;
    double m_dValue;
    int *m_pnValue;

public:
    Something() : m_nValue(0), m_dValue(0.0), m_pnValue(0)
    {
    }
};


Note : This syntax can be used with const member as well. For instance, if m_nValue was a const, it would had the same effect.

Thursday, November 12, 2015

C++ : copy constructor

We already know the basic constructor utility which is : initializing internal members. If not constructor is specified, the default constructor initializes each of class' members with their constructor.

Now let's take a look to the copy constructor :

Point (const Point & p);

This constructor will initialize our object by copying another one :

Point p1 (otherPoint);

Note: It is also possible to define our own copy constructor to define more specifically which members should be copied.

 
biz.