Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access member of derived class from pointer of base class

I have a class that is derived from another, I use an array of base class pointers to hold instances of the derived class, but because the array is of the base class, I cannot access members belonging to the derived class with pointer notation, is it possible for me to access these members with a simple command or should I just rewrite my base class to define the member and only use it in the 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;
}
like image 799
Stephen Avatar asked Apr 10 '16 02:04

Stephen


2 Answers

I cannot access members belonging to the derived class with pointer notation

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

is it possible for me to access these members with a simple command

You can do it if you perform static_cast<B*>(arr[0]) if you are 100% certain that the pointer points to B, but casting solution should be used as the last resort. Instead, you should derive 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;
    }
};
like image 99
Sergey Kalinichenko Avatar answered Oct 19 '22 23:10

Sergey Kalinichenko


Read about type-casting, it's a very basic and important aspect of the language.

In short, you can always cast a pointer-to-base to a pointer-to-derived, 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 that A* doesn't really point to an object of B type. If you try that on a C object, it will compile, and result in undefined behavior during runtime.

It should be mentioned however, that usually when one cannot be certain of the type of the object he refers to, a better design of the program could have prevented it from the first place. A common claim says that it is true for type casting in general.

P.S. Note that in your code, bar is a private member of class B (unintentionally, I assume. Any member of a class is private by default), hence cannot be accessed anyway outside of class B implementation.

like image 29
R.G. Avatar answered Oct 19 '22 23:10

R.G.