Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to call a derived class function that isn't defined in the base class using base class pointers. but this always raises the error:

error C2039: ‘derivedFunctionName’ : is not a member of ‘BaseClass’

Do you know how I could get around this?

Thanks,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
544 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can't call a member that appears only in a derived class through a pointer to the base class; you have to cast it (probably using dynamic_cast) to a pointer to the derived type, first -- otherwise the compiler has no idea the method even exists.

It might look something like this:

void someMethod(Base* bp) {
    Derived *dp = dynamic_cast<Derived*>(bp);
    if (dp != null)
        dp->methodInDerivedClass();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...