Cpp - class class Members

Introduction

You use the dot operator . to access the member functions and variables of that object.

Consider the following code

class Cart 
{ 
public: 
    int speed; 
    int wheelSize; 
    pedal(); 
    brake(); 
}; 

Cart class has a member variable called speed. To set this variable, use the dot operator:

Cart shoppingCart; 
shoppingCart.speed = 6; 
shoppingCart.pedal(); 

Private Versus Public Access

The Cart class has two public member variables and two public member functions.

The public keyword makes these parts of the class available to the public so that other classes and programs that use Cart objects.

All member variables and functions are private by default. Private members can be accessed only within functions of the class itself.

When the public keyword appears in a class definition, all member variables and functions after the keyword are public:

class Cart 
{ 
    int model = 110; 
public: 
    unsigned int speed; 
    unsigned int wheelSize; 
    pedal(); 
    brake(); 
}; 

The preceding code declares everything in the Cart class public except for the model member variable.

There's also a private keyword to make all subsequent member variables and functions private.

Each use of public or private changes access control from that point on to the end of the class or until the next access control keyword.

A function that sets or gets the value of a private member variable is called an accessor.

Other classes must call the accessor instead of working directly with the variable.

Related Topics

Exercise