Is it possible to return an abstract class(class itself or a reference, doesn't matter) from a function?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
You can return an abstract class pointer - assuming
B
is a concrete class derived from abstract classA
:or a reference:
or a smart pointer:
I know I'm little late but I hope this will help someone...
Being a newbie in C++ programming, I've also been stuck for a while on that problem. I wanted to create a factory method that returns an reference to an abstract object. My first solution using pointers worked well but I wanted to stay in a more "C++ manner". Here is the code snippet I wrote to demonstrate it:
Open to any critism !
The Factory design pattern is an example of returning a pointer to an abstract class object:
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.
Abstract classes cannot be instantiated and thus not returned.
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.