简体   繁体   中英

call sub class method from base class specific function

I've got a question concerning handling of virtual function in C++ programming. I have something like this:

template<class T>
class baseClass
{
    virtual void doSomething(T& t) {
        // some baseClass specific code
    }

    void doSomethingElse(T& t) {
        // some baseClass specific code

        this->doSomething(t);
    }
}

template<class T>
class subClass
{
    virtual void doSomething(T&) {
        // some subclass related code
    }
}

Now, if I construct an object of type subClass....

int main(int argc, char *argv[])
{
    subClass<anyType> * subClassObject = new subClass<anyType>();
    subClassObject->doSomethingElse(anyTypeObject);
}

.... and call the doSomethingElse method of the base class, this method will call the doSomething method of the base class and not of the sub class.

What I want to have, is calling the doSomething method of the subclass (not of the baseClass ).

Can anybody tell me how to accomplish that?

You could accomplish it with CRTP :

template<class T, class Derived>
class baseClass
{    
    void doSomethingElse(T& t) {
        // some baseClass specific code
        static_cast<Derived*>(this)->doSomething(t);
    }
}

template<class T>
class subClass : public baseClass<T, subClass>
{
    void doSomething(T&) {
        // some subclass related code
    }
}

See this for discussion about virtual template methods

I made several changes to your code to get it to compile, and with g++ 4.5 it indicates the subclass method is being called. Here's the code I compiled:

#include <iostream>

template<class T>
class baseClass
{
public:
    virtual void doSomething(T& t) {
        std::cout << "Base" << std::endl;
        // some baseClass specific code
    }

    void doSomethingElse(T& t) {
        // some baseClass specific code

        this->doSomething(t);
    }
};

template<class T>
class subClass : public baseClass<T>
{
    virtual void doSomething(T&) {
        std::cout << "Child" << std::endl;
        // some subclass related code
    }
};

int main()
{
    typedef int anyType;

    subClass<anyType> * subClassObject = new subClass<anyType>();
    int foo;
    subClassObject->doSomethingElse(foo);
}

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