Wednesday, March 25, 2009

Base Member Hiding in C++

Base class specifiers are explained in my previous blog. Here we will see how we could hide existing functionalities in a base class because in C++, it is not possible to remove functionality from a class.

Following code snippet from LearnCpp.com is used to explain this concept.

Base Class:

class Base  

{  

private:  

int m_nValue;  

 

public:  

    Base(int nValue)  

        : m_nValue(nValue)  

    {  

    }  

 

protected:  

void PrintValue() { cout << m_nValue; }  

}; 

Derived Class:

class Derived: public Base  

{  

public:  

    Derived(int nValue)  

        : Base(nValue)  

    {  

    }  

 

// Base::PrintValue was inherited as protected, so the public has no access

// But we're changing it to public by declaring it in the public section

    Base::PrintValue;  

}; 

This means the following code will work, as PrintValue is declared as public in the derived class.

int main()
{
    Derived cDerived(7);

    // PrintValue is public in Derived, so this is okay
    cDerived.PrintValue(); // prints 7
    return 0;
}

Conversely, here is another example where the code doesn’t work because of the Base Member variable is hidden as private in the derived function.

class Base
{
public:
    int m_nValue;
};

class Derived: public Base
{
private:
    Base::m_nValue;

public:
    Derived(int nValue)
    {
         m_nValue = nValue;
    }
};

int main()
{
    Derived cDerived(7);

    // The following won't work because m_nValue has been redefined as private
    cout << cDerived.m_nValue;

    return 0;
}

No comments:

Post a Comment