+ Reply to Thread
Results 1 to 2 of 2

Thread: Why below code works even though method is defined 'private'?

  1. #1
    Junior Member
    Join Date
    Jun 2012
    Posts
    26

    Why below code works even though method is defined 'private'?

    Code:

    Code:
    class CBase
    {
    public:
    	virtual int GetData()
    	{
    		return 10 ;
    	}
    } ;
    
    class CDerived : public CBase
    {
    private:
    	virtual int GetData()
    	{
    		return 10 ;
    	}
    } ;
    
    void MyFun()
    {
    	CBase *pBase = new CDerived() ;
    	int nData = pBase->GetData() ;
    }
    pBase can access private data member of the derived class even though it is declared "private".

    Why?

  2. #2
    You are quite right that it accesses the 'private' member function of the derive class.

    But when you compile the code, compiler sees that CBase can access the GetData method which is declared as public!

    This is compile time information that compiler can use.

    Compiler cannot identify the run-time information and hence could not identify the problem that you see.

+ Reply to Thread

Tags for this 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