access private members in inheritance

后端 未结 6 1354
余生分开走
余生分开走 2021-01-31 17:23

I have a class A, which have a field val declared as private. I want to declare a class B, that inherit from A and have an access to val. Is there a way to do it on C++?

<
相关标签:
6条回答
  • 2021-01-31 17:32

    Private members of a base class can only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :)

    class Base

    • public: can be accessed by anybody
    • private: can only be accessed by only base member functions (not derived classes)
    • protected: can be accessed by both base member functions and derived classes
    0 讨论(0)
  • 2021-01-31 17:34

    Well, if you have access to base class, you can declare class B as friend class. But as others explained it: because you can, it does not mean it's good idea. Use protected members, if you want derived classes to be able to access them.

    0 讨论(0)
  • 2021-01-31 17:36

    You can access the private members of a base class say A through an inherited member function of A

    #include<iostream>
    using namespace std;
    
    class A{
        int a;
        
        public:
        A(){};
        A(int val){a=val;};
        
        int get_a(){//To access a private variable it must be initialized here
            a=10;
            return a;
        }
    };
    
    class B: public A{
        int b;
        
        public:
        B(){};
        B(int val){b=val;};
        
        void get(){
            cout<<get_a();
        }
    };
    
    int main(){
        A ob1(2);
        cout<<ob1.get_a()<<endl;
        
        B ob2(4);
        ob2.get();
        
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-31 17:39

    Quick answer: You don't. Thats what the protected key-word is for, which you want to use if you want to grant access to subclasses but no-one else.

    private means that no-one has access to those variables, not even subclasses.

    If you cannot change code in A at all, maybe there is a public/protected access method for that variable. Otherwise these variables are not meant to be accessed from subclasses and only hacks can help (which I don't encourage!).

    0 讨论(0)
  • 2021-01-31 17:48

    You need to define it as protected. Protected members are inherited to child classes but are not accessible from the outside world.

    0 讨论(0)
  • 2021-01-31 17:49

    It is doable as describe in this Guru of the Week - GotW #76 - Uses and Abuses of Access Rights. But it's should be considered a last resort.

    0 讨论(0)
提交回复
热议问题