Is it possible to return an abstract class(class itself or a reference, doesn't matter) from a function?
Abstract classes cannot be instantiated and thus not returned.
You cannot return an actual class (a blueprint for creating objects). You can return an instance of a class though.
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.
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.
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;
}
The Factory design pattern is an example of returning a pointer to an abstract class object:
class Base
{ ; }
class One : public Base
{ ; }
class Two : public Base
{ ; }
Base * Factory(unsigned int number)
{
Base * p_item(NULL);
switch (number)
{
case 1:
p_item = new One;
break;
case 2:
p_item = new Two;
break;
default:
p_item = NULL;
break;
}
return p_item;
}
An actual abstract base class object can never be returned since there can never be an instance of an abstract base class. Pointers and references to an abstract base type can be returned as in the above example.
Pointers and references to an abstract base class returned from a function or method actually refer to a descendant of the abstract base type.