C++ Lesson 009: Member Functions

Minimal black and neon-green C++ Lesson 9 cover showing a single code editor scene with a Player member function

A member function is a function that belongs to a class. It lets an object perform an action using the data stored inside that object.

Start With a Game Score

In Lesson 8, we used classes to group related data. Now we can give a class an action.

#include <iostream>

class Player {
public:
    int score;

    void showScore() {
        std::cout << "Score: " << score << "\n";
    }
};

int main() {
    Player hero;
    hero.score = 100;
    hero.showScore();

    return 0;
}

showScore() is a member function because it is defined inside the Player class. The hero object calls it with hero.showScore().

Data and Actions Together

  • score is data stored by the object.
  • showScore() is an action the object can perform.
  • The dot operator connects the object to its member: hero.showScore().

Bitcoin Mining Example

#include <iostream>

class Miner {
public:
    bool running;

    void showStatus() {
        if (running) {
            std::cout << "Miner is on\n";
        } else {
            std::cout << "Miner is off\n";
        }
    }
};

The new programming idea is still the same: showStatus() belongs to Miner, so a Miner object can use that function to report its simple on/off state.

Sports Example

class Team {
public:
    int points;

    void addPoint() {
        points = points + 1;
    }
};

If a Team object calls addPoint(), its own points increase by one. The action and the data it changes stay together in the same class.

Video Reference

The freeCodeCamp C++ beginner course includes a dedicated Object Functions section that demonstrates functions attached to C++ objects. The embedded video begins near that part of the course.

Practice

  1. Create a class named Game.
  2. Add an integer named lives.
  3. Add a member function named showLives().
  4. Create one Game object and set lives to 3.
  5. Call showLives() with the object.

Key Takeaway

A member function is an action that belongs to a class. An object uses the dot operator to call that action. This keeps related data and behavior together.

Leave a comment