What is the point of a default argument set if the variables can’t be used?

Summary

The issue arises from a misunderstanding of how default arguments work in C++ constructors. The default argument is used to provide a value when the parameter is not supplied during object creation, but it does not automatically create a class member variable.

Root Cause

The root cause of the problem is the confusion between a constructor parameter and a class member variable. In the given example, x is a parameter of the constructor, not a member variable of the class.

Why This Happens in Real Systems

This happens in real systems because the syntax for default arguments in constructors can be misleading, especially for those new to C++. It seems to imply that the variable is part of the class, but in reality, it’s just a parameter that can have a default value if not provided.

Real-World Impact

The real-world impact is that developers might unintentionally create constructors with default arguments that seem useful but are actually not accessible as class members. This can lead to confusion and errors when trying to access or modify these “variables” within the class or from instances of the class.

Example or Code

#include 

class MyClass {
public:
    MyClass(int x = 123) : myX(x) {} // Initialize member variable myX with x
    void printX() { std::cout << myX << std::endl; }
    void plusOne() { myX++; }

private:
    int myX; // Declare myX as a member variable
};

int main() {
    MyClass myObject;
    myObject.printX(); // Prints 123
    myObject.plusOne();
    myObject.printX(); // Prints 124
    return 0;
}

How Senior Engineers Fix It

Senior engineers fix this issue by clearly distinguishing between constructor parameters and class member variables. They ensure that any variable intended to be part of the class's state is declared as a member variable and properly initialized in the constructor's initialization list.

Why Juniors Miss It

Juniors might miss this distinction due to a lack of experience with C++ or object-oriented programming principles. The syntax of default arguments in constructors can be misleading, and without a solid understanding of how constructors, parameters, and member variables interact, it's easy to confuse constructor parameters with class members.