What is the difference in passing arguments to the base class constructor?
Dog::Dog(string input_name, int input_age) : Pet(input_name, input_age) { }
Dog::Dog(string input_name, int input_age) { Pet(input_name, input_age); }
What is the difference in passing arguments to the base class constructor?
Dog::Dog(string input_name, int input_age) : Pet(input_name, input_age) { }
Dog::Dog(string input_name, int input_age) { Pet(input_name, input_age); }
Look the following snippet:
class Cat {
private:
const int m_legs;
public:
Cat() : m_legs{4}
{
}
};
In the snippet above this is the only way you have to initialize a constant because m_legs
is initialized before the body of constructor.
Another case is exeptions managment:
class Test {
private:
ICanThrow m_throw;
public:
Cat() try : m_throw{}
{
}
catch(...)
{
// mangage exception
}
};
I usually prefer initialize member before ctor body or when I can initialize members directly in the class declaration:
class Cat {
public:
void meow()
{
}
private:
const int m_legs = 4;
string m_meow{"meow"};
};
If Pet
has no default constructor, only 1) will work.
By the time you get into the actual body of the constructor all members and bases have already been constructed. So if a base class has no default constructor you need to tell the compiler which constructor you want it initialised with, and do it before the body of the constructor - this is what the initialiser list is for.
Another reason is if a base or member is const
- you can't modify it in the body of the constructor.