I'm having a specific problem which I've converted into the following Minimal, Complete, and Verifiable example.
#include <iostream>
class Foo {
public:
Foo(int v) : val(v) {}
int get_val() const
{
return val;
}
private:
int val;
};
class Parent {
public:
Parent() : member(0) {}
const Foo& get_member() const
{
return member;
}
protected:
Foo member;
};
// Nothing above this line should be changed
class Child : public Parent
{
public:
// This doesn't work (compile error)
//Child() Parent::member(1) {}
// Nor does this (also a compile error)
//Child() this->member(1) {}
};
int main()
{
Child x;
std::cout << x.get_member().get_val() << std::endl;
return 0;
}
This example demonstrates the issue I'm having in a larger software project where I'm inheriting from an external library but need to directly initialize one of the parent's member variables.
Unfortunately, the Parent class does not have a constructor which parameterizes its member's initialization.
If the Parent class had a constructor of the form
Parent(int val) : member(val) {}
then I could write a Child constructor as
Child() Parent::Parent(1) {}
but that is not the case for me.
Question: Is it possible to defer the initialization of a parent's member variable to an inherited class? If so, how?