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

Because of my device I can't use virtual functions. Suppose I have:

class Base
{
    void doSomething() { }
};

class Derived : public Base
{
    void doSomething() { }
};

// in any place
{
    Base *obj = new Derived;
    obj->doSomething();
}

the obj->doSomething() will call just the Base::doSomething()

Is there a way with Base *obj, to call the doSomething of the Derived?

I know I can just put a virtual before doSomething() of Base it solve the problem, but I'm limited by my device, the compiler doesn't support it.

See Question&Answers more detail:os

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

1 Answer

You could down cast the base class pointer to the derived class and call the function.

Base* obj = new Derived;
Derived* d = static_cast<Derived*>( obj ); 
d->doSomething();

Since doSomething() is not declared virtual, you should get the derived implementation.


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