简体   繁体   中英

Difference between passing arguments to the base class constructor in C++

将参数传递给基类构造函数有什么区别?

  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); }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM