Search code examples
c++syntaxconstructorinitializationmember-initialization

Why is accessing the members of a member object not allowed in a ctor?


class Edge:

class Edge {
    int dist = 0;
    std::pair<Node, Node> ends;
public:
    Edge() = default;
    explicit Edge(const int idist) : dist(idist) { }
    explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist) {
        ends.first = end1;
        ends.second = end2;
    }
    ~Edge() = default;
};

In the ctor explicit Edge(const int idist, Node& end1, Node& end2), why am I not allowed to use the syntax?:

explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist), ends.first(end1), ends.second(end2) { }

Solution

  • This is just not allowed. As the syntax of member initializer list,

    class-or-identifier ( expression-list(optional) ) (1) 
    class-or-identifier brace-init-list   (2) (since C++11)
    

    While ends.first and ends.second don't refer to class or identifier, they're expressions. You have to initialize ends in whole, e.g.

    explicit Edge(const int idist, Node& end1, Node& end2) : dist(idist), ends(end1, end2) { }