Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

c++ - How to call parent constructor in child classes constructor?

I have searched for it and this seems to be the only way of calling a superclass constructor in C++:

class SuperClass
{
    public:

        SuperClass(int foo)
        {
            // do something with foo
        }
};

class SubClass : public SuperClass
{
    public:

        SubClass(int foo, int bar)
        : SuperClass(foo)    // Call the superclass constructor in the subclass' initialization list.
        {
            // do something with bar
        }
};

But I'd like to know, how can I call the superclass constructor in the constructor body instead of initialization list?

I have to process inputs of my child's constructor and pass complex processed parameters to superclass constructor, how do I achieve that?

question from:https://stackoverflow.com/questions/66051940/how-to-call-parent-constructor-in-child-classes-constructor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A base class constructor must be run to initialize the base before you can enter the body of the derived class constructor. The Member Initializer List is the only way to initialize the base class. If you have complex requirements for the parameters, use helper functions to compute the parameters.

Example:

class SuperClass
{
    public:

        SuperClass(int foo)
        {
            // do something with foo
        }
};

class SubClass : public SuperClass
{
    private:
        static int basehelper(int foo)
        {
            // do complicated things to foo
            return result_of_complicated_things;
        }
    public:

        SubClass(int foo, int bar)
        : SuperClass(basehelper(foo))    // Call the superclass constructor in the subclass' initialization list.
        {
            // do something with bar
        }
};

If the base class parameters require knowledge known only as the derived class is constructed, you must either

  • Duplicate the effort,
  • Find a way to memoize the results of the helper (perhaps insert a layer of abstraction) and apply the results later in construction,
  • Modify the base class to have a simpler constructor and support Two-Phase Initialization, or
  • Do something entirely different. Perhaps Composition Over Inheritance is good advice for your use case.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...