简体   繁体   中英

C++ Taking the Base Class as an Input and Accessing Derived Class Member Functions

Say I have defined 2 classes, a base class and a derived class. Then I write a function that takes the base class as an input. When I use that function I will only ever pass in derived class functions and want to be able to access a redefined version of a base class method. So lets say both the base and derived class have a method foo(). I create a derived class variable and pass it into a function that only accepts base class variables. Inside that function I want to access foo() as it is defined in the derived class, not as it is defined in the base class. I have tried protected but that doesn't work.

Make the function virtual and that will access the derived class implementation on a base class pointer if the pointer points to a derived class instance.

Make sure you are passing a pointer or a reference (NOT passing the object by value)

class BaseT
{
    public: virtual void f(string msg) { cout << msg << " from Base" << endl; }
};

class DerivedT: public BaseT
{
    public: void f(string msg) { cout << msg << " from Derived" << endl; }
};

// myFunc says hi from derived or from base
// depending on what b really points to

void myFunc (BaseT *b) { b->f("hi"); }  

int main(int argc, char* argv[])
{   
    DerivedT d;
    BaseT b;

    myFunc (&d);
    myFunc (&b);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM