Search code examples
c++pointersinheritanceconstructorsuperclass

C++ inheritance, sending a pointer to base class


I have a ninjaCreep class that is derived from a class Creep. I want to pass the pointer that I have acquired through the parameters of the derived class to the base class' constructor however I am getting this error:

../ninjacreep.cpp|4|error: no match for ‘operator*’ (operand type is >‘Ogre::SceneManager’)|

The code:

ninjaCreep::ninjaCreep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id)
        : Creep(*sceneManager, x, y ,z, id) //line 4
{
    //ctor
}

I have never passed a pointer to a base class before, so I think the error lies somewhere there?

Creep constructor has the same parameters as ninjaCreep:

Creep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id);

Solution

  • You just have to use the parameters as they originally are:

    ninjaCreep::ninjaCreep(Ogre::SceneManager& sceneManager, int x, int y, int z, std::string id)
            : Creep(sceneManager, x, y ,z, id) //line 4 no "*"
    {
        //ctor
    }
    

    sceneManager is not a pointer: it's a reference to an object of type SceneManger. It is to be used a normal SceneManager object, without any dereference.

    Important note:

    & can be part of a type declaration:

    int a 
    int &i=a ;  // i is a reference.  you can then use i and a interchangeably
    

    It is not be confused with the address taking operator:

    int a; 
    int *pa = &a;  // pa is a pointer to a.  It contains the adress of a. 
                   // You can then use *pa and a interchangeably
                   // until another address is assigned to pa.