Use access modifiers to utilize encapsulation and hide class implementations from calling code. - C++ Class

C++ examples for Class:Member Access

Description

Use access modifiers to utilize encapsulation and hide class implementations from calling code.

Demo Code

#include <cinttypes>
#include <iostream>

using namespace std;

class Car/*ww w.j a va 2s .  c o  m*/
{
private:
    int m_NumberOfWheels;

public:
    void SetNumberOfWheels(int numberOfWheels)
    {
        m_NumberOfWheels = numberOfWheels;
    }

    int GetNumberOfWheels()
    {
        return m_NumberOfWheels;
    }
};

int main(int argc, char* argv[])
{
    Car myCar;
    // myCar.m_NumberOfWheels = 4; -Access error
    myCar.SetNumberOfWheels(4);

    cout << "Number of wheels: " << myCar.GetNumberOfWheels() << endl;

    Car myMotorcycle;
    myMotorcycle.SetNumberOfWheels(2);

    cout << "Number of wheels: " << myMotorcycle.GetNumberOfWheels() << endl;

    return 0;
}

Result


Related Tutorials