Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning an abstract class from a function

People also ask

Can you return an abstract class?

No, a abstract type can't be returned directly , You should return a subclasses of abstract classes .

Can we return a class from a function?

When you create an object in any function it's destroyed as soon as the function execution is finished just like in variables. But when you return a object from a function firstly compiler creates a local instance of this object in heap called unnamed_temporary then destroyes the object you created.

How do you inherit an abstract class in C++?

Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class. The compiler will not allow the declaration of object d because D2 is an abstract class; it inherited the pure virtual function f() from AB .

Why do we use abstract class in C++?

The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error.


You can return an abstract class pointer - assuming B is a concrete class derived from abstract class A:

A * f() {
    return new B;
}

or a reference:

A & f() {
    static B b;
    return b;
}

or a smart pointer:

std::unique_ptr<A> f() {
    return std::make_unique<B>(...);
}

You can declare the return type to be a reference or pointer to the abstract class, so that it can be assigned to references or pointers to the abstract class and used based on its interface.

However, you cannot return an actual instance of the actual abstract class because by definition you cannot instantiate it. You could, however, return instances of concrete subtypes which is good enough because by the principle of substitution, you should always be able to use a subtype instead of a supertype.


No, but a function could have a return type of a pointer (or a reference) to an abstract class. It would then return instances of a class that is derived from the abstract class.


Abstract classes cannot be instantiated and thus not returned.