Question

I've class G.


class B : public G

class A : public B


class D : public G

class C : public D


class F : public G

class E : public F


From a different class, I've an access to G (G sorry!!). I've to get some memeber of class A (for example, string m_Astr).

How can I access the A string? If I use pure virtual in class G, I'll have to implement this getStr function in E and C in addition to the implementation of A, and I need it for A only.

please help

Was it helpful?

Solution

If you know (somehow) that the object pointed to is actually an instance of an A, then you can use static_cast:

G* p = get_the_thing();
A* a = static_cast <A*> (p); // OK

However, if the object pointed to by p above doesn't instantiate an A, then the above code will yield undefined behavior.

A more safe approach would be to use dynamic_cast,

G* p = get_the_thing();
A* a = dynamic_cast <A*> (p); // OK

Here, a will be NULL if p isn't actually an A. However, dynamic_cast can only be used in this manner with polymorphic classes: the base class must have at least one virtual function. A virtual destructor would do nicely here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top