G
G
gotoxy2015-12-13 14:33:10
OOP
gotoxy, 2015-12-13 14:33:10

Is it possible to return descendants of an abstract class from a function?

There is a function that, depending on the input value, creates an object of a certain class, which is inherited from the abstract one. Is it possible somehow to return this object by reference to the base class, without creating it through new and not by pointer?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MiiNiPaa, 2015-12-13
@gotoxy

Yes, you can.

#include <iostream>

struct Abstract
{
    virtual void print() = 0;
    virtual ~Abstract() = default;
};

struct Concrete : Abstract
{
    virtual void print() override
    {
        std::cout << "Concrete\n";   
    }

};

Abstract& foo()
{
   static Concrete c;
   return c;   
}

int main()
{
    foo().print();
}
coliru.stacked-crooked.com/a/cedf0ea1d25f9a12

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question