1

I know it's OK to call base class function in a derived class constructor, because base class is constructed before derived class.But I'm not sure if this is a good practice.Example code is:

class Base {
 public:
  int Get() const { return i_; }
  void Set(const int i) { i_ = i; }

 private:
  int i_{0};
};

class Derived : public Base {
  // initialize `derived_i_` with a call to base class function, Is this a good
  // practice in production code?
  Derived() : derived_i_{Get()} {
    // do some other things
  }

 private:
  int derived_i_{0};
};

7
  • How should Base::Get() ever return something different but 0 when called from the member initialization list of Derived()? Commented May 8, 2019 at 2:08
  • @Swordfish This is just a example, i_ may changes. Commented May 8, 2019 at 2:09
  • i_ may change – How? Commented May 8, 2019 at 2:10
  • @Swordfish OK, I made a mistake, i_ will never change. Commented May 8, 2019 at 2:14
  • Maybe you find a better example then. Commented May 8, 2019 at 2:15

1 Answer 1

1

To be more pedantic, you could write your constructor as the following:

Derived() : Base(), derived_i_{Get()} {
  // do some other things
}

The compiler should fully construct the base class before doing any initialization of the derived class.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.