Reputation: 2070
I'm implementing a class that inherits from a superclass. The superclass requires arguments for its constructor. I would like the subclass to be instantiatable without requiring arguments. The superclass looks like this:
class OtherClass {
public:
OtherClass(YetAnotherClass *yac);
};
class SuperClass {
public:
SuperClass(OtherClass *c);
};
I'd like to do something like this:
class MyClass : public SuperClass {
public:
MyClass() : SuperClass(OtherClass(YetAnotherClass)) {}
};
In order to avoid having to do something like this when instantiating a member of MyClass
:
YetAnotherClass * only_used_once = YetAnotherClass();
OtherClass * also_used_just_once = OtherClass(only_used_once);
MyClass what_i_actually_want = MyClass(also_used_just_once);
Is this possible? A similar question showed the solution of creating a static method that produces the arguments needed for the parent constructor, but I would hope there's a simpler way to get there.
Upvotes: 1
Views: 56
Reputation: 217283
With :
struct DataClass
{
DataClass() : yetAnotherClass(), otherClass(&yetAnotherClass) {}
YetAnotherClass yetAnotherClass;
OtherClass otherClass;
};
If each instance of MyClass
owns the other class you may do the following:
class MyClass : private DataClass, public SuperClass
{
public:
MyClass() : DataClass(), SuperClass(&this->otherClass) {}
};
else they share the other class and you may do:
class MyClass : public SuperClass
{
public:
MyClass() : SuperClass(&dataClass.otherClass) {}
private:
static DataClass dataClass;
};
DataClass MyClass::dataClass;
Upvotes: 1