Friday, 29 June 2007

Can access a private function?

Today, at lunch time, Anand had a slip in his hand with C++ code written on it. He was smiling showing that to me and asking to tell how the code behaves.

As usual he had a great feeling of discovering some new thing ;)

I had to watch the code, it goes like below

Class CBase
{
    public:
        virtual void vfunc()
        {
            // Some definition
        }
};

 

Class CDerived : public CBase
{
    private:
        void vfunc()
        {
            // Some definition
        }
};

 

int main()
{
    CBase *pBase = new CDerived();
    pBase->vfunc();
}

CBase has a virtual function vfunc which is overridden in CDerived. In the main routine we are making a base pointer to point to the derived class instance. Then we are calling the vfunc.

The main point to note here is - CDerived::vfunc() is private.

Even the function is declared as private its accessible! when we do

pBase->vfunc();

Strange!

This is because the real call to the function is made thru virtual pointer.

We wouldn't be able to access the same function via an instance of CDerived. Isn't it?

What to say about this? Is this a design flaw? A loop hole? or just say "This is what C++ is"!

4 comments:

Anonymous said...

I need to understand about this first. When we declare a member function under private specifier, what is the exact thing happening behind like at the OS level or compiler level or Hardware level in order to disallow invoking the function from outside (ie from main())????

Anand Patil said...

Fix the memory leak in sample code. ;)

Prashanth Narayanaswamy said...

@Ibrahim

I dont think there will be any OS level protection for private or protected functions. All member functions irrespective of their access rights, will be there in the code segment.
The only thing that puts the restriction is the compiler. During compilation time only, he does a symatic check and reports error if any private functions are accessed via an instance of that class.

Deepak Dhananjaya said...

@prashanth,
Good observation, but, its not a flaw or overlooked feature in C++ ;)

When we have a virtual function, the access is specified when it is declared, and not when it is OVERRIDDEN. The rules for access of a virtual function is not affected by the rules for the function that overrides, and more over, when a reference to an object is used to invoke the virtual function it means the "the declaration" has to be taken from the class of which the reference is of type, and not of the class to which the reference it points to.
In practical situations, this is one of the strengths of "C++" :)