How to access the derived class's data from one of its instances' member function that receives a pointer to the base class? I have:
class Base{
public:
virtual void compare(Base*)=0;
};
class A: public Base{
int x;
public:
A();
void compare(Base*);
};
class B: public Base{
char c;
public:
void compare(Base*);
};
A::A(){
x = 1;
};
void A::compare(Base *p){
cout<< "A's x is " << x << "\n";
cout<< "Argument's x is " << p->x;
};
void B::compare(Base* p){
cout<< "B's compare() is running\n";
};
int main(const int argc, const char *argv[]){
A a1 = A();
A a2 = A();
B b = B();
a1.compare(&a2);
}
which won't work since Base
doesn't have data member x
. While I was writing this it came to me that this would not be such a good idea to access a data member of the derived class through a pointer to the Base interface class.
In my problem I need to compare different derived classes with the same interface provided by Base
class. Base
's interface must include compare(Base*)
member function. The way instances are compared may vary among derived classed. The logic of comparison should apparently be coded inside those classes' member functions. How should I implement this model?