Access to a derived class from a base class pointer

I have a class that is derived from another, I use an array of pointers of the base class to store instances of the derived class, but since the array has a base class, I cannot access elements belonging to the derived class with a pointer, is it possible for me to access to these elements with a simple command or just rewrite my base class to define a member and use it only in a derived class?

Example:

class A { public: int foo; }; class B : public A { public: char bar; }; class C : public A { int tea; }; int main() { A * arr[5]; arr[0] = new B; char test = arr[0]->bar; //visual studio highlights this with an error "class A has no member bar" return 0; } 
+5
source share
3 answers

I cannot access elements belonging to a derived class with a note label

This is by design: you did not tell the compiler that the object pointed to by the pointer is of a derived type.

is it possible to access these elements with a simple command

You can do this if you execute static_cast<B*>(arr[0]) , if you are 100% sure that the pointer points to B , but the casting decision should be used as a last resort. Instead, you should get a member function in the base class and provide an implementation in the derived class:

 class A { public: int foo; virtual char get_bar() = 0; }; class B : public A { char bar; public: char get_bar() { return bar; } }; 
+6
source

Read tip-casting , this is a very simple and important aspect of the language.

In short, you can always refer a pointer to a base to a pointer to a derivative, and then refer to its unique public members.

 A * arr[5]; arr[0] = new B; char test = static_cast<B*>(arr[0])->bar; 

However, the last line above is a valid statement, even if this A* does not point to an object of type B If you try this on a C object, it will compile and lead to undefined behavior at runtime.

It should be noted, however, that, as a rule, when a person cannot be sure of the type of object to which he refers, a better program design could prevent him from the very beginning. The general statement says that this is true for type typing in general.

PS Please note that in your code, bar is a private member of class B (unintentionally, I assume that any class member is private by default), so it cannot be accessed in any case outside of the implementation of class B

+1
source

In the case of your code, your member of the derived class is private. Thus, you cannot access it from the base class. If you want to access, you must change the member of the derived class to "public". You should fix your code as follows:

 class B : public A { public: char bar; }; int main() { A * arr[5]; arr[0] = new B; char test = static_cast <B *>(arr[0])->bar; //visual studio highlights this with an error "class A has no member bar" return 0; 

}

0
source

Source: https://habr.com/ru/post/1246801/


All Articles