Accessing private member from derived class Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Accessing private member from derived class without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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?

Answer

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”.

We are here to answer your question about Accessing private member from derived class - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts