Home > Net >  Accessing private member from derived class
Accessing private member from derived class

Time:11-03

This might be a trivial question. Have below code,

class message {
public:
    virtual void setMessage(const string& name, const int& age, const string& title) const;
    virtual void getMessage(const string& name) const;
private:
    void removeMessage(const string& name);
};

class test : public message {
public:
    using message::removeMessage;
};


int main()
{
    test t;
    t.removeMessage("_");

    while (1);
    return 0;
}

Trying to expose removeMessage() as a public method from the test class. But this is giving error that,

error C2876: 'message': not all overloads are accessible

How to expose a private method in base class as public in derived class?

CodePudding user response:

You cant. Private means it is only accessible in the class it is defined in, and subclasses do not meet this definition. You probably want the protected keyword.

class message {
public:
    virtual void setMessage(const string& name, const int& age, const string& title) const;
    virtual void getMessage(const string& name) const;
protected: //use protected instead
    void removeMessage(const string& name);
};

class test : public message {
public:
    using message::removeMessage;
};


int main()
{
    test t;
    t.removeMessage("_");

    while (1);
    return 0;
}

Protected can be summed up as "private, but accessible in base classes aswell".

CodePudding user response:

Private members can never be accessed on derived classes. If your intention is to have the derived class access the members of the base class then make those protected or public.

  •  Tags:  
  • c
  • Related