-2

What is the difference in passing arguments to the base class constructor?

  1. Dog::Dog(string input_name, int input_age) : Pet(input_name, input_age) { }
  2. Dog::Dog(string input_name, int input_age) { Pet(input_name, input_age); }
boriaz50
  • 860
  • 4
  • 17
  • 4
    One calls the parent constructor. The other creates a temporary `Pet` object which is immediately thrown away and destructed (well at least if you add the missing semicolon, so it actually builds). – Some programmer dude Oct 03 '17 at 14:17

2 Answers2

1

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"};
};
Elvis Dukaj
  • 7,142
  • 12
  • 43
  • 85
0

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.

virgesmith
  • 762
  • 1
  • 7
  • 18