Reputation: 1528
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;
}
Upvotes: 5
Views: 1627
Reputation: 135
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.
Upvotes: 1
Reputation: 1
In case of your code, your member of derived class is private. So, you can not access it from base class. If you want to access, you must change the member of derived class to "public". You should fix your code like this:
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;
}
Upvotes: 0
Reputation: 727077
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;
}
};
Upvotes: 6