Possible mistake in constructor initialization chapter

class DependencyExample {
private:
    std::string name;           // Declared first
    int nameLength;             // Declared second - depends on name
    
public:
    // WRONG: nameLength depends on name, but name isn't initialized yet
    DependencyExample(const std::string& n)
        : nameLength(n.length()), name(n) {
        // nameLength will be garbage because name isn't initialized yet!
    }
    
    // CORRECT: Declare members in dependency order
    DependencyExample(const std::string& n)
        : name(n), nameLength(name.length()) {
        // name is initialized first, then nameLength
    }
};

// nameLength will be garbage because name isn’t initialized yet!
is not true because compiler will initialize it in order of which members are declared. It was mentioned just before this.

You’re right. nameLength will not be garbage.

The order of initialization would be name = n and then namelength = n.size() in the first constructor as well. Since n is always defined, the answer, namelength will still be defined. Let me think of a better example.

class DependencyExample {
private:
    int nameLength;             // Declared first - but depends on name!
    std::string name;           // Declared second!
    
public:
    // WRONG: nameLength depends on name, but name isn't initialized yet
    DependencyExample(const std::string& n)
        : name(n), nameLength(name.size()) {
        // nameLength will be garbage because name isn't initialized yet!
    }
    
    // CORRECT: Declare members in dependency order
    DependencyExample(const std::string& n)
        : nameLength(n.size()), name(n) {
        // name is initialized first, then nameLength
    }
};

This is the example I wanted to bring up here. nameLength is always going to be undefined because it is dependent on name.size() which is not initialized at the time of being called.

1 Like