2

Hi Stackoverflow Community, I need your assistance! I am learning inheritance currently I have a simple two class hierarchy, "User" as the parent and "Admin" as the child class. In protected in the "User" class I have the member variable "std::string m_sRank" and want that to be automatically initalized to the rank corresponding the class name - being "User". For some reason in the child class "Admin" I can't initialize the m_sRank to "Admin" despite the member variable being in the "protected" scope. I'm using a constructor in both classes and initalizing list. Can someone provide me a solution to this problem as I have quite literally spent hours trying. Any help would be greatly appreciated. I hope I have explained myself sufficently, and I am happy to clarify if I have not made sense.

class clsUser
{
    private:

protected:
    std::string m_sRank;
public:
     //IT WORKS HERE! I can automatically set the "User" class member variable to "Admin"
    clsUser() : m_sRank("User"){}
};



class clsAdmin : public clsUser
{
private:
public:
     //Doesn't work here despite "m_sRank" being in the protected scope in the parent class
    clsAdmin() :m_sRank("Admin") {}
};


void DisplayUserDetails(clsUser *objAdmin) 
{
    std::cout << "***" << std::endl;
    std::cout << "Name: " << objAdmin->GetName() << std::endl;
    std::cout << "Age: " << objAdmin->GetAge() << std::endl;
    std::cout << "Rank: " << objAdmin->GetRank() << std::endl;
    std::cout << "***" << std::endl;
}


int main()
{
    clsUser objUser();
    clsAdmin objAdmin();

    DisplayUserDetails(&objUser);

    DisplayUserDetails(&objAdmin);

1 Answers1

2

Yes, you cannot initialise parent attributes in that fashion. You need to invoke the parent constructor in this fashion. Note that string m_sRank could also be const given that it is initialised by the member initialiser list:

using std::string;

class clsUser
{
...
protected:
    string m_sRank;

public:
    clsUser() : m_sRank("User"){}
    explicit clsUser (string const&& rank) : m_sRank(rank) {}
...
};



class clsAdmin : public clsUser
{
...
public:
    clsAdmin() : clsUser("Admin") {}
...
};


You may notice the use of the explicit keyword, see this article for an explanation of the corner-case that has led to it being recommended for all single-parameter constructors: http://sjbrown.co.uk/2004/05/01/always-use-explicit/

cigien
  • 57,834
  • 11
  • 73
  • 112
Den-Jason
  • 2,395
  • 1
  • 22
  • 17