Reputation: 327
I am trying to create a derived class object and populate the data-members (coming from base class) with a existing base class object.
In my process lifecycle, I already had a base class object. For some decision, I have to create a new object (derived from base class). One way to do this is expose the assessors and copy the data. Is there any solution like aggregate initialization or dynamic_cast that I could use instead?
#include <iostream>
#include <string>
using namespace std;
class Base {
protected:
string name_;
public:
Base() : name_ ("foo")
{
}
void ChangeName()
{
name_ = std::string {"bar"};
}
};
class Child final : Base {
public:
string GetName()
{
return name_;
}
};
int main()
{
Base b;
b.ChangeName();
Child c = {b};
cout<<"Hello World. Here is my name: " << c.GetName() << endl;
return 0;
}
Expected Output: Hello World. Here is my name: bar
Compilation Error
try.cpp:33:17: error: could not convert ‘{b}’ from ‘<brace-enclosed initializer list>’ to ‘Child’
Child c = {b};
Upvotes: 2
Views: 1774
Reputation: 1159
Something like this is possible using the C-style casts:
Child c(*(Child*)&b);
But I wouldn't advise you to use this. It can fail if the memory layouts of the classes aren't similar. The equivalent C++ cast for this situation is this:
Child c(*reinterpret_cast<Child*>(&b));
EDIT: Turns out this is Undefined Behavior. Don't attempt this :)
Upvotes: -1
Reputation: 32732
If you want to construct a Child
from a Base
, you need to add a constructor to Child
that will do that:
Child(const Base &b): Base(b) { }
You need to be cautious using this, as it will allow constructing a Child
from another class that is also derived from Base
. And if Child
has any other data members, you need to be sure to add appropriate initialization or default values for them.
Upvotes: 5