Question

In the following example, will I be using dynamic dispatch to call the virtual functions?

struct Base{
    virtual double fn(){return 3.2;}
};
struct Deri1 : public Base{
    using Base::fn;
}
struct Deri2 : public Base{
    virtual double fn(){return 4.6;}
}

The classes I'm implementing contain much more information, but there is some that I want to keep default for some derived classes but override in others, the fn() in above code is an example of this. Basically, I'm just using the base class to avoid rewritting fn() every time it's not overridden. Is this the right way?

Thanks!

Était-ce utile?

La solution

One can avoid dynamic dispatch by avoiding the 'virtual' keyword in the definition of the function, so long as one doesn't uses pointers, as explained in this link.

This creates some complications with generic methods and polymorphism. If one is using dynamic polymorphism, one would pass a pointer to the base class to a method, in which case the 'virtual' keyword is necessary for the pointer to determine which method to use. One can define a static polymorphic method using templates, as explained in the following link.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top