Complex c ++ merge function

I have:

class XILightSource { public: virtual XVec2 position() const = 0; }; class XLightSprite : public XSprite, public XILightSource { }; 

The problem is that XSprite already has the same position function. How can I tell the compiler that I want to use the XSprite::position function as an implementation of XILightSource::position() ?

+6
source share
4 answers

override it and call XILightSource :: position ():

 class XLightSprite : public XSprite, public XILightSource { public: XVec2 position() const { return XSprite::position(); } }; 
+6
source

Just add one line:

 class XLightSprite : public XSprite, public XILightSource { public: using XSprite::position; }; 
0
source

In fact, you do not need to do anything special.

By default, the implementation of XVec2 position() const in XLightSprite will hide the position() of XSprite and will act as an override of the virtual function defined in XLightSource .

If, however, you want to clarify that your intention is to override the function, you can add a declaration of use

 class XLightSprite : public XSprite, public XILightSource { public: using XSprite::position; XVec2 position() const; }; 

Note that if position () from XSprite is also a virtual function in the same format, the new implementation will also act as an override of position in XSprite.

0
source

If class XSprite already has this feature, the best way is to make XSprite child of XILightSource (since it's abstract). The advantage of this approach is that you don't have to rely on multiple inheritance unnecessarily. i.e.

 class XILightSource { public: virtual XVec2 position() const = 0; }; class XSprite : public XILightSource { public: virtual XVec2 position() const { ... } }; class XLightSprite : public XSprite { }; 
0
source

Source: https://habr.com/ru/post/898809/


All Articles