This simple example demonstrates the C++ syntax for calling base class constructors - as far as I understand it as a C++ learner:
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 take named arguments to the derived class constructor as input.
Now, what if I want to call BaseClass()
constructor with an input value that is not a direct input to DerivedClass()
? Basically, I'd like to do some multiline work with x
and y
within DerivedClass()
, then pass a calculated value to BaseClass()
. Can this be done with constructors? Should this be done with some kind of initializer method instead?
You can do that, 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 that you can even make compute()
a non-static method but be aware that DerivedClass
or BaseClass
members won't be initialized at the time of the call. So you won't be able to rely on their values.
If you're using C++11 or newer 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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With