I have a Parent class with a number of children. Each function in the Parent class is pure i.e. there are no parent implementations of the functions but the children have their own implementations. No need to post code there - standard stuff.
I don't want people creating direct instantiations of the parent class from anywhere. I have safe-guarded against this by having the virtual functions being pure so that's fine.
My problem: Depending on a user's input (a string), I want to instantiate one of the children. I only know which one at runtime. My (incorrect?) idea was the following which compiles fine and works fine until I put the code into a function and return the parent.
So this works:
Parent* parent;
if(user_input == "A") {
Child1 child1;
parent = &child1;
}
else if(user_input == "B") {
Child2 child2;
parent = &child2;
}
but this does not work:
Parent* foo(string user_input) {
Parent* parent;
if(user_input == "A") {
Child1 child1;
parent = &child1;
}
else if(user_input == "B") {
Child2 child2;
parent = &child2;
}
return parent;
}
When I say it doesn't work I mean, it compiles but then I get a segmentation error when I do this:
Parent* parent = foo(user_input);
parent->some_child_function(); // segmentation error here
I'm sure it's a stupid/simple question about me not fully understanding pointers??? Well after reading all about them in books/articles, I still don't know what I'm doing wrong.... It's probably a one-line fix?
Thank you :).