swooders
swooders

Reputation: 189

Downcasting C++ Objects

I have a base class (which is not abstract) which defines methods that its subclasses inherit. I have another program which has an methods that have as output the an object of the base class type.

class A {
   //methods
};
class B : public A {
   //more methods
};

A function() { //return some instance of A}

I want to define functions in terms of object A but then use them for object B. E.g.

B obj = function()

I've looked into dynamic casts, but that seems to require I cast pointers. Is there any way to down-cast instances of objects without using pointers?

Upvotes: 1

Views: 520

Answers (2)

eerorika
eerorika

Reputation: 238461

Is there any way to down-cast instances of objects without using pointers?

You can down cast references as well, so technically you don't need pointers.


You can convert a base class object to a derived type if the derived type has a converting constructor. For example, you might copy-construct the base subobject:

struct B : A {
   B(const A& a): A(a) {}
};
// ...
B obj = function();

However, this is not "down casting", which is "the act of casting a reference of a base class to one of its derived classes." (quote from wikipedia, emphasis mine). In the quoted context, reference is a more general term that encompasses references, pointers and other indirection.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60037

No.

You are trying to give an object something it does not have.

Upvotes: 2

Related Questions