How to call derived class method from base class pointer?

前端 未结 1 1562
春和景丽
春和景丽 2020-12-03 06:41

I have a class structure similar to the following

class A
{
public:
    A(void);
    ~A(void);

    void DoSomething(         


        
相关标签:
1条回答
  • 2020-12-03 07:24

    You need to make DoSomething() a virtual function in both classes to get the polymorphic behavior you're after:

    virtual void DoSomething(int i) { ...
    

    You don't need to implement virtual functions in every sub class, as shown in the following example:

    #include <iostream>
    
    class A {
        public:
            virtual void print_me(void) {
                std::cout << "I'm A" << std::endl;
            }
    
            virtual ~A() {}
    };
    
    class B : public A {
        public:
            virtual void print_me(void) {
                std::cout << "I'm B" << std::endl;
            }
    };
    
    class C : public A {
    };
    
    int main() {
    
        A a;
        B b;
        C c;
    
        A* p = &a;
        p->print_me();
    
        p = &b;
        p->print_me();
    
        p = &c;
        p->print_me();
    
        return 0;
    }
    

    Output:

    I'm A
    I'm B
    I'm A

    0 讨论(0)
提交回复
热议问题