i have a problem in properly handling method overriding where an abstract class is present inside my classes hierarchy. I'll try to explain:
class AbstractClass{
public:
virtual void anyMethod() = 0;
};
class A : public AbstractClass {
void anyMethod() {
// A implementation of anyMethod
cout << "A";
}
};
class B : public AbstractClass {
void anyMethod() {
// B implementation of anyMethod
cout << "B";
}
};
AbstractClass *ptrA, *ptrB;
ptrA = new A();
ptrB = new B();
ptrA->anyMethod(); //prints A
ptrB->anyMethod(); //prints B
Ok..previous example work fine .. the concrete implementation of the AbstractClass method anyMethod will be called at run time. But AbstractClass is derived from another base class which has a method not virtual called anyMethod:
class OtherClass {
public:
void anyMethod() {
cout << "OtherClass";
}
};
class AbstractClass : public OtherClass {
public:
virtual void anyMethod() = 0;
};
//A and B declared the same way as described before.
Now , if i try something like that:
ptrA = new A();
ptrB = new B();
ptrA->anyMethod(); //prints OtherClass
ptrB->anyMethod(); //prints OtherClass
What am I misunderstanding? Is there any solution for making ptrA and ptrB printing A and B without using cast, typeid, etc?
Why don't you do:
class OtherClass
{
public:
virtual void anyMethod()
{
cout << "OtherClass";
};
}
That should solve your problems
If anyMethod
was declared virtual in the base class to which you have a pointer or reference, it should be looked up virtually and print A and B correctly. If it wasn't, then there is nothing you can do (beyond changing it to be virtual).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With