Wednesday, October 28, 2009

C++ Gyan of the day: Friend class and Inheritance

Check if the following code snippet is proper.

/*
 * Copyright (C) 2009 Raghavendra Nayak
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// Program to explain the Friend class and inheritance

#include <iostream>
#include <cstdlib>

////////////////////////////////////////////////////////////////////////////////

class someClass {
public:
    void printData() {
        std::cout<<"The value of m_data is "<<m_data;
    }
private:
    int m_data;

    // declare BaseClass as the friend class to this class
    friend class BaseClass;
};

////////////////////////////////////////////////////////////////////////////////

class BaseClass {
public:
    /// @brief The BaseClass constructor.
    BaseClass() {
        std::cout<<"In BaseClass constructor.\n"
                 <<"Setting the m_data to 10.\n";
        // set m_data to 10
        m_someClassObject.m_data = 10;
        // print the set value using printData method.
        m_someClassObject.printData();
    }
protected:
    someClass m_someClassObject;
};

////////////////////////////////////////////////////////////////////////////////

class DerivedClass : public BaseClass {
public:
    /// @brief The DerivedClass constructor.
    DerivedClass() {
        std::cout<<"In DerivedClass constructor.\n"
                 <<"Setting the m_data to 20.\n";
        // set m_data to 20
        m_someClassObject.m_data = 20;
        // print the set value using printData method.
        m_someClassObject.printData();
    }
};

int main(int /*argc*/, char */*argv*/[])
{
    DerivedClass derivedClassObject;

    return EXIT_SUCCESS;
}

If you try to compile this, you will end up with compilation errors. the reason is in the comments.

Technorati tags: .

3 comments: