I’m working on a C++ 23 project and I’m confused about the best way to set default values for member variables in a class. I’ve seen several different methods and I’m not sure which one is best.
Here’s an example class Student
with name
and age
as member variables:
1. In-Class Member Initializers:
class Student {
public:
Student() = default;
Student(const std::string& name, int age) : name(name), age(age) {}
private:
std::string name{""};
int age{0};
};
2. Initializer List in Constructor:
class Student {
public:
Student() : name(""), age(0) {}
Student(const std::string& name, int age) : name(name), age(age) {}
private:
std::string name;
int age;
};
3. Initialize in Constructor Body:
class Student {
public:
Student() {
name = "";
age = 0;
}
Student(const std::string& name, int age) : name(name), age(age) {}
private:
std::string name;
int age;
};
4. No Default Initialization:
class Student {
public:
Student(const std::string& name, int age) : name(name), age(age) {}
private:
std::string name;
int age;
};
While method 1 (in-class member initializers) is syntactic sugar for method 2 (initializer lists in constructors), I’m asking what is considered best practice. I want to maintain consistency in my project. Even though they might be the same internally, I’d like to know when to choose one over the other, or if there are any guidelines for better consistency.
Also, do I even need to set default values, or is it okay (or when is it okay) to only have a constructor with parameters (like in example 4)?