Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing child class members using pointer to a base abstact class

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.

like image 899
user1873947 Avatar asked Feb 11 '13 20:02

user1873947


1 Answers

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();
like image 56
Andy Prowl Avatar answered Sep 29 '22 07:09

Andy Prowl