1
votes

What's the C++ way of returning a derived type as a abstract type in a function with this caveat?

Say the function creates a derived type and wants to return that object as the abstract base type. How do you do that in C++ without resorting to messy C like pointers?

1
You resort to nice C++ like smart pointers.Igor Tandetnik
Just a point of clarification before I start reading up on smart pointers. Is that the only way to handle this sort of problem in C++?G4143
If you want to use abstract classes you have to use pointers. And smart pointers are the best way to go.Timo
@Justin No, that's what you do instead of using abstract classes, but it's poor because you have to list all the possibilities and then deal with them explicitly with conditional code.Barmar

1 Answers

-1
votes

Are you asking for example code? Hopefully this helps...

class Mammal {
public:
    virtual void Speak() const = 0; 
};

class Dog : public Mammal {
public:
    void Speak() const {
        cout << "Woof Woof" << endl;
    }
};

Mammal* getDog() {
    return new Dog();
}

int main() {
    Mammal* m = getDog();
    m->Speak();
    delete m;
    return 0;
}