C++ examples for Class:Member Access
Use access modifiers to utilize encapsulation and hide class implementations from calling 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; }