user63898 user63898 - 14 days ago 8
C++ Question

C++ pass to function implementation object as interface type

I have interface that looks like this :

class GameObject
{
public:
virtual ObjType getType() = 0;
virtual void setType(ObjType ot) = 0;

protected:
ObjType objtype;


};


then i have class that implement this interface

class SpriteObject : public GameObject
{
public:
SpriteObject();
virtual ~SpriteObject();
ObjType getType() { return objtype; }
void setType(ObjType ot) { objtype = ot; }

private:

};



class LayerObject : public GameObject
{
public:
LayerObject ();
virtual ~LayerObject ();
ObjType getType() { return objtype; }
void setType(ObjType ot) { objtype = ot; }

private:

};


in the main class i have function which i try to pass the SpriteObject to
That looks like this :

bool HelloWorld::NodeAction(GameObject* &pGameObj)
{
}


when i try to do :

SpriteObject *pSpriteObject = new SpriteObject();
NodeAction(pSpriteObject);


im getting this error:

error C2664: 'bool HelloWorld::NodeAction(GameObject *&)' : cannot convert argument 1 from 'SpriteObject *' to 'GameObject *&'


In the end i want to have global function that can get different Objects that implement GameObject .

Answer

This function:

bool HelloWorld::NodeAction(GameObject* &pGameObj)

expects a non-cv lvalue reference of GameObject*.

Because pSpriteObject is a lvalue of type SpriteObject *, there're no match function to call for it, it will try to use implicit conversion to find an overload function by those conversion:

  • Lvalue to rvalue conversion

    A glvalue of any non-function, non-array type T can be implicitly converted to a prvalue of the same type. If T is a non-class type, this conversion also removes cv-qualifiers.

  • Pointer conversions

    A prvalue pointer to a (optionally cv-qualified) derived class type can be converted to a prvalue pointer to its (identically cv-qualified) base class.

Hence, this line

NodeAction(pSpriteObject);

expects a function with one of those prototypes:

bool HelloWorld::NodeAction(GameObject*)
bool HelloWorld::NodeAction(GameObject* const&)
bool HelloWorld::NodeAction(GameObject* &&)

All is acceptable but

bool HelloWorld::NodeAction(GameObject*)

should be preferred, see this question. With primitive type, pass by value should be faster than pass-by-reference even if pre-C++11