class a //my base abstract class
{
public:
virtual void foo() = 0;
};
class b : public a //my child class with new member object
{
public:
void foo()
{}
int obj;
};
int main()
{
b bee;
a * ptr = &bee;
ptr->obj; //ERROR: class a has no member named "obj"
}
My question is, how can I access the "obj" member when I have a pointer to base class ("a") pointing to child class ("b") object? I know that casting should do the trick but I'm looking for better solutions.
You can use the dynamic_cast<>
operator to convert a pointer to a
to a pointer to b
. The conversion will succeed only if the run-time type of the object pointed to by ptr
is b
, and will return a null pointer otherwise, so you must check the outcome after converting:
b* p = dynamic_cast<b*>(ptr);
if (p != nullptr)
{
// It is safe to dereference p
p->foo();
}
If you can guarantee that the type of the object pointed to by ptr
is b
, however, in this case (since no virtual inheritance is involved) you can even use a static_cast<>
, which incurs in less overhead because it is performed at compile-time.
b* p = static_cast<b*>(ptr);
// You are assuming ptr points to an instance of b. If your assumption is
// correct, dereferencing p is safe
p->foo();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With