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.
dynamic_cast<> a b. , , ptr, b, , :
dynamic_cast<>
a
b
ptr
b* p = dynamic_cast<b*>(ptr); if (p != nullptr) { // It is safe to dereference p p->foo(); }
, , ptr, b, , ( ) static_cast<>, , .
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();
. dynamic_cast , , , , .
dynamic_cast
GCC Clang ( Visual Studio, )
if (Derived* x = dynamic_cast<Derived*>(x)) { // do something with \c x now that we know its defined }
++ 11, auto,
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.
x
if
else if