devxlogo

When is a mem-initializer required?

When is a mem-initializer required?

A const member or a reference member cannot be initialized within an object’s constructor. Instead, they must be initialized in the constructor’s member-initializer list. Conceptually, mem-initialization takes place before the constructor, so by the time it is invoked, all const and reference members have already been assigned a value:

 class mem {	int &ri;  const int k; //both must be mem-initialized 	mem(int i, int j) : ri(i), k(j) {} };

Similarly, when a constructor in a derived class has to pass arguments to its base class constructor, a mem-initializer must be used:

 class base {	int num1;	char * text;	//no default constructor, arguments must be supplied	base(int n1, char * t) {num1 = n1; text = t; }};class derived : public base {	char *buf	derived (int n, char * t) : base(n, t) { buf = new char[100];}};
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist