I want to inject some basic information into a derived class that it can build on. The derived class shouldn't care about initializing those information, it should be just there.
That alone would be easily possible through inheritance. But the problem is that the base class doesn't know the values on its own. Instead, they need to be passed in as parameter. However, since the derived class should not need to take care of that, tunneling the parameters through the derived constructor which calls the base constructor with it is no option.
The only solution I can think of is to make the information available statically so that the base class can get them without help. But I'd like to avoid that.
Is there some way of first creating and initializing the base class and extending the instance to a derived type afterwards? If not, how can I achieve this order of creation and dependencies using the available features of C++?
#include <string>
#include <iostream>
using namespace std;
class Base {
public:
Base(string name, int age) : name(name), age(age) {}
protected:
const string name;
int age = 0;
};
class Derived : public Base {
Derived() { // No parameters here, no call to base constructor
cout << "My name is " << name << " and I'm " << age << "." << endl;
}
}
Base base("Peter", 42);
Derived derived(base); // "My name is Peter and I'm 42."
If you want to create a derived class instance using the base class instance then there is some conversion rule between the two, which you can specify explicitly using a derived class constructor. Share Improve this answer Follow answered May 28 '19 at 23:45 Nick PershynNick Pershyn 3944 bronze badges Add a comment | 0
1 Your base class should simply provide a virtual method to clone the instance. The derived class should pass the correct type to the factory. – jxh Jul 14 '15 at 1:38
5 1 You cannot change the type of an instance. The best you can do is replace the instance with one of the derived class type. Can you post the code around the place you need to do this? Maybe we can show you how to do the replacement. – Daniel T. Jul 14 '15 at 1:15
"The information should just be there" sounds to me like it allows two possible interpretations:
The information is in fact globally constant and can be hard-coded:
Derived() : Base("Peter", 42) {}
What you really meant was that "the base should just be there":
Derived(const Base & b) : Base(b) {}
Extending an already-allocated type to a derived type is not possible for a reason: if the derived type added fields, how would you determine the correct size upfront?
A possible way is only a constructor accepting a Base
instance, or maybe an operator=
.
However you may want to consider using composition over inheritance in this example. If Base
only serves as template for Derived
, it is not a good example of an inheritance relationship.
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