Access elements of a child class using a pointer to the abstact base 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 member "obj" when I have a pointer to the base class ("a") pointing to the object of the child class ("b")? I know that casting should do the trick, but I'm looking for the best solutions.

+5
source share
3 answers

dynamic_cast<> a b. , , ptr, b, , :

b* p = dynamic_cast<b*>(ptr);
if (p != nullptr)
{
    // It is safe to dereference p
    p->foo();
}

, , ptr, b, , ( ) static_cast<>, , .

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();
+7

. dynamic_cast , , , , .

+3

GCC Clang ( Visual Studio, )

if (Derived* x = dynamic_cast<Derived*>(x)) {
     // do something with \c x now that we know its defined     
}

++ 11, auto,

if (auto x = dynamic_cast<Derived*>(x)) {
     // do something with \c x now that we know its defined     
}

, ,

if (const auto x = dynamic_cast<Derived*>(x)) {
     // read something from \c x now that we know its defined     
}

, x if, , dynamic_cast , if else if.

+1

All Articles