Member Initializer Lists
Learn about member initializer lists in C++
Member initializer list allows us to initialize data members of an object without writing assignment statements in a constructor. Without further ado, here is an example:
C++
#include <iostream>#define PI 3.1416using namespace std;class Sphere {private:const double density;double radius;public:Sphere(double r) : radius(r), density(4.3) {// The following initialization wouldn't work, because density is a const// density = 4.3;}double volume() {return 4 * PI * radius * radius * radius / 3;}double mass() {return density * volume();}};int main() {// your code goes hereSphere s(3.2);cout << "Volume: " << s.volume() << ", mass: " << s.mass();return 0;}
Our Sphere
class stores the radius
and density
of a sphere. We have defined functions to obtain the volume and mass of the sphere. The constructor uses member initializer list on line ...