samedi 25 juin 2016
how to return an abstract class using c++
Been running into a snag while working in C++. I've tried several answers on SO, as well as other places (like: returning an abstract class from a function, and How do I make an abstract class properly return a concrete instance of another abstract class?), but I've still been having trouble-- these don't seem to completely fit...
I have an abstract class, a derived class:
class AbstractClass {
virtual std::string virtMethod() = 0;
}
class Derived : public AbstractClass {
std::string virtMethod();
}
Also, I a separate class which I'm trying to get a return type of the abstract class (of course, returning an instance of the derived class).
I've tried using pointer and reference:
AbstractClass* methodFromOtherClass() {
if (somethingIsTrue) {
Derived d = Derived();
return &d;
}
SomeOtherDerived s = SomeOtherDerived();
return &s;
}
Which, in Xcode, gives me the warning:
Address of stack memory associated with local variable 'd' returned
I tried creating a static Derived object and was unable to then destroy it in the method which calls my "methodFromOtherClass()."
I've also tried my hand at smart pointers (though someone may point out my obvious misuse of them):
std::unique_ptr<AbstractClass> methodFromOtherClass() {
if (somethingIsTrue) {
Derived d = Derived();
return std::unique_ptr<AstractClass>(&d);
}
SomeOtherDerived s = SomeOtherDerived();
return std::unique_ptr<AstractClass>(&s);
}
The above, perhaps unsurprisingly, gives me a segfault.
I'm used to being able to do this easily in Java... Any help would be appreciated. C++ isn't a very strong language for me at the moment, so it could be something very basic which I'm overlooking.
Inscription à :
Publier les commentaires (Atom)
Aucun commentaire:
Enregistrer un commentaire