C ++: calling base class constructor with computed argument

This simple example demonstrates C ++ syntax for invoking base class constructors - as far as I understand it as a C ++ student:

class BaseClass { protected: int i; public: BaseClass(int x) { i = x; } }; class DerivedClass: public BaseClass { int j; public: DerivedClass(int x, int y): BaseClass(y) { j = x; } 

Here, the base class constructor can accept named arguments to the derived class constructor as input.

Now, if I want to call the BaseClass() constructor with an input value that is not a direct input to DerivedClass() ? Basically, I would like to do multi-line work with x and y inside DerivedClass() , and then pass the calculated value to BaseClass() . Can this be done using constructors? Should this be done using some kind of initialization method?

+6
source share
3 answers

You can do it, yes:

 class BaseClass { public: BaseClass(int x) : i(x) {} private: int i; }; class DerivedClass: public BaseClass { public: DerivedClass(int x, int y): BaseClass(compute(x, y)), // Neither i or j are initialized here yet j(x) {} private: static int compute(int a, int b) { return a + b; } // Or whatever int j; }; 

Note: you can even make compute() non-static method, but remember that DerivedClass or BaseClass members will not be initialized during a call. Thus, you cannot rely on your values.

+11
source

If you are using C ++ 11 or later, you can also use lambda expressions:

 class BaseClass { public: BaseClass(int x) : i(x) {} private: int i; }; class DerivedClass: public BaseClass { public: DerivedClass(int x, int y): BaseClass( [=]()->int { int sum = 0; for(int i = 0; i < x; ++i) { sum += y + i * x; } return sum; }()), j(x) {} private: int j; }; 
+3
source

Then you can do this:

 DerivedClass(int x, int y): BaseClass(compute(x,y)), j(y) { //j = x; //use member-initialization-list ---> ^^^^ } int compute(int x, int y) { //your code } 
+2
source

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


All Articles