Home > Software design >  How do I access private member variables with public member functions (derived class)?
How do I access private member variables with public member functions (derived class)?

Time:07-14

I need to get access of the base class private member variables using public member functions from the derived class. That means, I can call it anytime in a public member function from the derived class and change it anytime.

For example:

# include <iostream>
using namespace std;

class A
{
private:
    int a = 19;
    public:
    int getA() // Function to get A
    {
        return a;
    }
};

class B : public A
{
    public:
    void getAatB() // How do I get a variable at parent class (A)?
    {
        cout<<getA();
    }
};

int main()
{
    B a;
    a.getAatB();
    return 0;
}

I need to get access to variable a. How do I do this without changing private to protected or public at class A?

CodePudding user response:

the easy way of doing that is adding friend class B; to class A , so class B can access class A's attributes and you aren't going to need change private to protected.

CodePudding user response:

If you want only the descendants of A having a access to getA() member function, there is a special keyword protected in c . The purpose of protected, as stated here is.

Class members declared as protected can be used only by the following:

  • Member functions of the class that originally declared these members.

  • Friends of the class that originally declared these members.

  • Classes derived with public or protected access from the class that originally declared these members.

  • Direct privately derived classes that also have private access to protected members.

  • Related