...
/Non-Static Data Members Initialization in C++11
Non-Static Data Members Initialization in C++11
Here, you’ll see how to add default values for data members with a new C++11 feature.
We'll cover the following...
Handling default values
You can initialize data members in various constructors, delegate them to reuse code, and inherit from base classes. Yet, we can still improve at assigning default values for data members!
See below:
Press + to interact
#include <iostream>#include <string>class Car {public:Car() { }int GetSeats() const { return seats_; }double GetMaxVelocity() const { return maxVelocity_; }std::string GetName() const { return name_; }private:int seats_ = 0;double maxVelocity_ = 0.0;std::string name_ { "default"} ;};int main() {Car oldCar;std::cout << "seats: " << oldCar.GetSeats() << '\n';std::cout << "velocity: " << oldCar.GetMaxVelocity() << '\n';std::cout << "name: " << oldCar.GetName() << '\n';}
As you can see, the variables are assigned their default values in the place of being declared individually. There’s no need to set values inside a constructor. It’s much better than using a default constructor because it brings declaration and initialization code together. This way, it’s harder to leave data members uninitialized!
The feature is called non-static data member initialization, or NSDMI ...