I got this code:
#include <iostream>
#include <string>
using namespace std;
struct Base {
Base(string name) {
this->name = name;
}
string name;
};
struct Derived: Base {
string name2;
};
template <typename T>
T createNode(string name) {
Base* node = new Base(name);
return static_cast<T>(node);
}
int main() {
Derived* node = createNode<Derived*>("hej");
node->name2 = "bajs";
cout << node->name2;
}
And the node->name2 = "bajs";
line causes (random) segmentation fault. I'm just wondering how I can correct this to not cause segmentation fault. I still want to call createNode()
to create the base node and set all the property members after. Is it doable in c++
?