Invoke a default constructor from a non-default constructor?

I have invoked constructors before but it was always with inheritance. Suppose I wrote the following

1
2
3
4
5
6
7
8
9
10
11
12
class Animal() {
public:

Animal() : legs(4), hungerLevel(0) {}
Animal(int happiness) : Animal(), this->happiness(happiness) {};
// Note how I'm calling the default constructor.

private:
int legs;
int hungerLevel;
int happiness;
}


Would this not work on mainstream compilers?
https://msdn.microsoft.com/en-us/library/dn387583.aspx#Anchor_2
You can’t do member initialization in a constructor that delegates to another constructor


1
2
3
Animal(int happiness) : Animal(){
   this->happiness = happiness;
}
Hi,

An alternate view :

Just thinking that a delegating ctor is handy if you have more than one ctor wanting to do the delegating, with perhaps one target ctor. At the moment you could achieve the same thing by assigning values in the class definition:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Animal() {
public:

// Animal() : legs(4), hungerLevel(0) {}
Animal(const int happiness) : happiness(happiness) {}; // better if had different name for the parameter
// Note how I'm calling the default constructor.

private:
std::size_t legs = {4};  // assignment here the same as if member init list used, C++11
                                 // it's really direct initialisation, rather than assignment
int hungerLevel= {0};   // maybe these could be std::size_t
int happiness;            // as well ?
};


So this means that these values are initialised in all cases, so that wouldn't be ideal if one ctor wanted to set legs to 8 say. Another alternative is to use default arguments.

So the advantages of this are: that you don't have to delegate any more; you don't have a default ctor (can use the implicit one if needed); can avoid the rule of five; avoids assignment in a ctor body.

The this-> isn't necessary here (in the init list), but a different name for the parameter might be handy if you wanted to refer to the parameter itself.

Make sure that all of your ctor initialise all the members, your OP didn't do that, but I realise it may have been a quick example.

Anyway, I hope this has helped, even a little bit :+)

Regards
Topic archived. No new replies allowed.