C++ Default Constructor Called

前端 未结 3 900
醉酒成梦
醉酒成梦 2021-01-29 01:36

In the code below, class B has a member that is of type class A (varA1). I want to create a class B object where the member varA1 is intended to use the non-default constructor

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-29 02:10

    Use a member initialization list:

    B::B(int v1) : var1(v1), varA1(v1) {
        cout << "B int constructor" << endl;
    }
    

    Note that members are initialized (constructed) in the same order that they're declared in the class, so switching orders in the member initialization list won't change the order in which construction happens (and hopefully your compiler will warn you of this). This little detail becomes important if you try to construct varA1 from var1 and var1 is declared after varA1 in the class definition.


    And by the way, all this line does (inside the B::B(int v1) constructor):

    A varA1(int v1);
    

    is forward declare a function named varA1 that takes an int parameter and returns an A object. This is semi-similar to the most vexing parse, though this isn't really a case of the most vexing parse.

提交回复
热议问题