If I have a class, let's call it class A
that is derived from a class called class B
, is it possible to return an object of class B
from my derived object of class A
?
Asked
Active
Viewed 629 times
0

user0042
- 7,917
- 3
- 24
- 39

JosephTLyons
- 2,075
- 16
- 39
-
4The answer is most likely yes if I understand correctly. Could you please give us a [MCVE] so we can be sure? Especially the part with "_from my derived object_", what object? – Hatted Rooster Aug 22 '17 at 21:43
-
Yes, as long as the return type is the base class. – Omid CompSCI Aug 22 '17 at 21:44
-
1Possible duplicate of [What is object slicing?](https://stackoverflow.com/questions/274626/what-is-object-slicing) – Stephan Lechner Aug 22 '17 at 21:45
-
Well ,yeah. If `B` is not abstract, it is possible to return one by value. The problem is then how you obtain the object to return. If it is obtained by slicing an `A`, you need to be careful to ensure consistency. If it is obtained by creating a new instance of `A`, things are easier. If `B` is abstract, it is not possible to create an instance of it - the most you can do is obtain an instance of a derived class, obtain a reference or pointer to it, and ensure the object continues to exist as long as the reference or pointer is used. – Peter Aug 22 '17 at 22:23
-
@Raindrop7 I'm working with a massive C++ library. It has a ton of built in functions that require a certain data type to be passed into them, but I'd like to modify this data type slightly by inheriting it into my class and adding some bools and strings and methods. This new object would only be for my personal methods and functions, but I still need to be able to pass it into the functions of the library I'm working with and they most certainly won't accept my derived class objects, so I need to be able to return the base object to pass into those library functions. – JosephTLyons Aug 22 '17 at 22:31
-
@Peter B is not an abstract class, so this should work pretty easily I guess. – JosephTLyons Aug 22 '17 at 22:32
2 Answers
1
If I have a class, let's call it
Class A
that is derived from a class calledClass B
, is it possible to return an object ofClass B
from my derived object ofClass A
?
Sure that's possible:
class B {
// ...
};
class A : public B {
public:
// Not that this is explicitly necessary:
B& getAsB() { return *this; }
};
It's also valid to write simply:
A a;
B& b = a;
Though doing something like
A a;
B b = a;
will create a copy and slice your original A
to B
.

user0042
- 7,917
- 3
- 24
- 39
-2
Yes, it is possible, but it's not remarkable in any way.
struct B {}; // using struct instead of class for convenience
struct A // may or may not inherit from B
{
B ReturnSomeObject()
{
return B();
}
};
int main()
{
A object1;
B object2 = object1.ReturnSomeObject();
}
Here, even though there is no inheritance, a method in class A
can return an object of class B
. If you add inheritance
struct A: B
{
...
};
it still works.

anatolyg
- 26,506
- 9
- 60
- 134