Home > Software engineering >  C possible to call function with same name in different class with single pointer?
C possible to call function with same name in different class with single pointer?

Time:07-12

Is it possible to call run() with p without concerning different class they are(for example class cast on a void*) and different implementation of run() in each class?

class A
{
    void func()
    {
        //new B
        //new C
        //new D
        //*p points to the instance of one of B,C,D
        p->run(i);
    }
    // some pointer *p
}

class B
{
    void run(int i);
}

class C: public B
{
    void run(int i);
}

class D: public B
{
    void run(int i);
}

CodePudding user response:

This works:

#include <iostream>

class B
{
    public:
    virtual int run(int i);
};

class A
{
    public:
    int func(B* obj, int i)
    {
        return obj->run(i);
    }
};



class C: public B
{
    public:
    virtual int run(int i){ return 2*i;}
};

class D: public B
{
    public:
    virtual int run(int i){ return 3*i;}
};

int main(){
    A a;

    C obj1;
    D obj2;

    B* ptr1 = &obj1;
    B* ptr2 = &obj2;

    std::cout << a.func(ptr1, 3) << "\n";
    std::cout << a.func(ptr2, 3) << "\n";
}
  •  Tags:  
  • c
  • Related