2

Considering the code below:

#include <iostream>

class tester
{
public:
    tester(){}
    explicit tester(double val) : 
        m_a(val) // I assume this now overwrites the "default" initialise value?
    {}
    double m_a {1.123}; // Default constructor value?
};


int main()
{
    tester t1;
    tester t2(2.456);

    std::cout << "t1:" << t1.m_a << std::endl;
    std::cout << "t2:" << t2.m_a << std::endl;

    return 0;
}

My question is, can you have both the initialise value in the class and in the constructor body? - how does the compiler resolve this? It appears that the constructor wins since the output of this program is:

t1:1.123
t2:2.456
code_fodder
  • 15,263
  • 17
  • 90
  • 167

1 Answers1

3

Yes, for default member initializer,

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.

In the default constructor m_a is not mentioned in member initializer list, then it will be initialized by the default member initializer as 1.123. In tester::tester(double) m_a will be initialized by the member initializer list as the argument val.

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405