What are the rules for calling the superclass constructor?

前端 未结 10 2180
甜味超标
甜味超标 2020-11-21 23:18

What are the C++ rules for calling the superclass constructor from a subclass one?

For example, I know in Java, you must do it as the first line of the subclass cons

10条回答
  •  广开言路
    2020-11-22 00:09

    In C++, the no-argument constructors for all superclasses and member variables are called for you, before entering your constructor. If you want to pass them arguments, there is a separate syntax for this called "constructor chaining", which looks like this:

    class Sub : public Base
    {
      Sub(int x, int y)
      : Base(x), member(y)
      {
      }
      Type member;
    };
    

    If anything run at this point throws, the bases/members which had previously completed construction have their destructors called and the exception is rethrown to to the caller. If you want to catch exceptions during chaining, you must use a function try block:

    class Sub : public Base
    {
      Sub(int x, int y)
      try : Base(x), member(y)
      {
        // function body goes here
      } catch(const ExceptionType &e) {
        throw kaboom();
      }
      Type member;
    };
    

    In this form, note that the try block is the body of the function, rather than being inside the body of the function; this allows it to catch exceptions thrown by implicit or explicit member and base class initializations, as well as during the body of the function. However, if a function catch block does not throw a different exception, the runtime will rethrow the original error; exceptions during initialization cannot be ignored.

提交回复
热议问题