Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ and inheritance in abstract classes

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?

like image 352
Heisenbug Avatar asked Dec 22 '22 18:12

Heisenbug


2 Answers

Why don't you do:

class OtherClass 
{
    public:
    virtual void anyMethod()
    {
       cout << "OtherClass";
    };
}

That should solve your problems

like image 158
Grammin Avatar answered Dec 24 '22 07:12

Grammin


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).

like image 39
Puppy Avatar answered Dec 24 '22 06:12

Puppy