Search code examples
c++inheritancemethodssuperclass

C++ unable to use super class' methods?


I feel stupid right now, haven't been doing C++ in ages, can't understand what's wrong... However I got this following class:

#include <string>
class NamedObject
{
    public:
        NamedObject();
        virtual ~NamedObject();
        virtual std::string getName() const { return m_name };
        virtual void setName(const std::string name) { m_name = name };
    private:
        std::string m_name;
};

And now I'm inheriting a simple class out of it:

#include "NamedObject.h"
enum eTeam { eAttacker, eDefender, eSpectator, eNone };
class Player : public NamedObject
{
    public:
        Player();
        virtual ~Player();
        virtual void printName();
        virtual eTeam getTeam() const { return m_team };
        virtual void setTeam(const eTeam team) { m_team = team };
    private:
        std::string m_name;
        eTeam m_team;
};

However, I am unable to use player->setName("blabla") from my main.cpp? Here's the main file:

#include "Player.h"
int main()
{
    Player* p1 = new Player();
    p1->setName("Name Changed!")
    p1->printName(); // prints "Unnamed" since I declared that in default ctor
    return 0;
}

I'm not getting any errors, everything runs up well, the name just doesn't simply change. Also, I got all of the constructors and destructors, as well as my printName-method working perfectly, and the problem is not within them.


Solution

  • What you see is that setName modifies the m_name in the parent class and printName prints out the m_name of the derived class because you're redeclaring std::string m_name; in the derived class.

    Remove the declaration from the derived class and mark m_name as protected member in the parent class:

    #include <string>
    class NamedObject
    {
    public:
        NamedObject();
        virtual ~NamedObject();
        virtual std::string getName() const { return m_name };
        virtual void setName(const std::string name) { m_name = name };
    protected:
        std::string m_name;
    };
    

    You could also keep m_name private and use the method getName() instead, as suggested by moswald.