+ Reply to Thread
Results 1 to 2 of 2

Thread: What is class access modifiers in C++?

  1. #1

    What is class access modifiers in C++?

    Hi all,

    What is class access modifiers in C++?

    Thanks

  2. #2
    Senior Member
    Join Date
    Feb 2012
    Posts
    109
    Hi,

    A class in C++ can expose its services to client.
    It also has some internal state that it does not want to share directly.
    It allows its client to use some property to access those state.

    This way class can hide its data from external world which is data hiding feature of C++.

    There are three kind of modifiers in class.
    a. private
    Only class can access these members.
    b. protected
    Only class and its derived can access these members.
    c. public
    Anyone can access these members.

    Code:
    class CModifiers
    {
    private:
    	int m_nPrivate ;
    
    protected:
    	int m_nProtected ;
    
    public:
    	int m_nPublic ;
    
    	CModifiers()
    	{
    		m_nPrivate		= 0 ;
    		m_nProtected	= 1 ;
    		m_nPublic		= 2 ;
    	}
    
    	int GetPrivate()
    	{
    		return m_nPrivate ;
    	}
    	
    	int GetProtected()
    	{
    		return m_nProtected ;
    	}
    } ;
    
    class CDerived : public CModifiers
    {
    public:
    
    	CDerived()
    	{
    	}
    
    	void SetProtectedValue(int nNewProtectedValue)
    	{
    		m_nProtected = nNewProtectedValue ;
    	}
    } ;
    
    void UseModifiers()
    {
    	 CDerived objDerived ;
    
    	 //int nPrivate	= objDerived.m_nPrivate ; //'m_nPrivate' : cannot access private member declared in class 'CModifiers'
    	 int nPrivate	= objDerived.GetPrivate() ; //It works as GetPrivate is declared as public!
    	 
    	 //int nProtected = objDerived.m_nProtected ; //'m_nProtected' : cannot access protected member declared in class 'CModifiers'
    	 int nProtected = objDerived.GetProtected() ;	//It works as GetProtected is declared as public!
    
    	 objDerived.SetProtectedValue(10) ; // change the value... Derived can access the protected member of the base class!
    	 nProtected = objDerived.GetProtected() ;	//It works as GetProtected is declared as public!
    
    	 //Client (a user who resides outside of the class) of CModifiers (a class) can access ***only*** public members of that class. 
    	 //There are some exception to this like 'friend' keyword and a derived class.
    	 int nPublic = objDerived.m_nPublic ;
    }
    Hope this helps.

    Regards.

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts