C ++ function call before initializing base class in initialization list

Scenario:

In the project, I have class B , which is derived from class A , where class A has an invalid default constructor.

class B set as follows:

 class B : public A { private: void SetupFunction() { /*Crucial code*/ } public: B() : A(Value) {} } 

Suppose that when calling SetupFunction() during initialization before the constructor A(Value) you need to decide how I would do it? Is it possible?

I am using Code::Blocks 13.12 on Windows 7

+4
source share
2 answers

You can make SetupFunction() return a value that is then passed to initialise A , for example:

 class B : public A { private: int SetupFunction() { /*Crucial code*/ return Value; } public: B() : A(SetupFunction()) {} } 

Or use a comma if you don't want to change SetupFunction() :

 class B : public A { private: void SetupFunction() { /*Crucial code*/ } public: B() : A((SetupFunction(), Value)) {} } 
+10
source

The standard tries to get A built before B So, as you ask, this is not possible.

If A has a constructor for each case, this can be done.

 class A { public: structB { int dummy}; A( const structB &){ /* body of setup function */} ... }; 

Then similar behavior could be done. You currently do not have B, only constructor options.

0
source

Source: https://habr.com/ru/post/1269014/


All Articles