Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Apr 16, 1998

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];}
};
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date