c++ class constructors

Started by
5 comments, last by joanusdmentia 19 years, 7 months ago
In doing some reading recently I cam accross the following construct:

class MyClass
   {
   public:
   
      MyClass() : integer(23) { }

      int integer;
   };
        
What is the purpose of doing that instead of this:

class MyClass
   {
   public:
   
      MyClass() { integer = 23; }

      int integer;
   };
        
It is foolish for a wise man to be silent, but wise for a fool.
Advertisement
Mostly just preference.
It invokes the copy constructor instead of the default destructor, then operator=. It doesn't matter on built-in types, though.
Not giving is not stealing.
It is called the member initialization list, and what it does is initialize your member variables at construction, as opposed to after construction. It is like:

int num = 0; (initializer list)

vs.

int num;
num = 0; (assignment after initialization to bogus value)

Initializer lists can be useful for example when you have constant member variables (which cannot be assigned a value after construction).

Regards,
jflanglois
Ok thanks. I was getting worried there for a sec... It's simular to how you call the constructor of a parent class.
It is foolish for a wise man to be silent, but wise for a fool.
Quote:Original post by TheRealMAN11
It's simular to how you call the constructor of a parent class.


Yes... and the same way you initialise 'reference' attributes

E.g.:
class foo{public:    foo():my_bar(a_bar),my_const_bar(c_bar){};private: bar& my_bar; const bar& my_const_bar;}
To elaborate a bit more it's particularly useful when you have objects where the constructor and assignment operators are expensive. If you initialise the object in the constructor then the default constructor is invoked when the container is created, followed by the assignment inside the container's constructor. If you use the initialiser list only the constructor of your choice will be executed.
"Voilà! In view, a humble vaudevillian veteran, cast vicariously as both victim and villain by the vicissitudes of Fate. This visage, no mere veneer of vanity, is a vestige of the vox populi, now vacant, vanished. However, this valorous visitation of a bygone vexation stands vivified, and has vowed to vanquish these venal and virulent vermin vanguarding vice and vouchsafing the violently vicious and voracious violation of volition. The only verdict is vengeance; a vendetta held as a votive, not in vain, for the value and veracity of such shall one day vindicate the vigilant and the virtuous. Verily, this vichyssoise of verbiage veers most verbose, so let me simply add that it's my very good honor to meet you and you may call me V.".....V

This topic is closed to new replies.

Advertisement