I have the following program:
#include <iostream>
class Base {};
class Deriv : public Base
{
public:
int data;
Deriv(int data): data(data) {}
};
int main()
{
Base *t = new Deriv(2);
std::cout << t->data << std::endl;
}
When I compile it, I’m getting the error:
x.cpp: In function ‘int main()’:
x.cpp:15:21: error: ‘class Base’ has no member named ‘data’
How can I get access to data field (note that I don’t want to use Deriv *t = new Deriv(2))?
You have declared your pointer to be of type
Baseand the compiler is correct, there is no memberdatain that class. You would need to cast the pointer back up to aDeriv*in order to access the member in this way. Why are you making the pointer of type to the base class anyway? This is only usually useful when you have a polymorphic class hierarchy.You could consider using a virtual function to return the value of this member, but without knowing what your classes and code is trying to achieve it is hard to recommend one way or the other. Based on your small code sample, simply using
instead, seems a better choice