Defining and Utilizing Methods

Lesson Introduction

Welcome! Today, we're diving into an essential topic in C++ programming: defining and utilizing methods. Methods, also known as member functions, are functions inside a class that can access its members. By the end of this lesson, you'll know how to define methods and call these methods to perform operations.

Importance of Methods

Why do we need methods? Imagine you have a robot. This robot can do tasks like walking, talking, and picking up items. In programming, these tasks are methods that belong to the robot class. Methods help organize our code, making it easier to manage and understand.

Defining a Method

Let's define a simple class with a method. In C++, methods are defined in a class.

Here's an example:

#include <iostream>

class Robot {
public:
    // Method to make the robot talk
    void talk() {
        std::cout << "Hello, I am a robot!" << std::endl;  // Output: Hello, I am a robot!
    }
};

Here, we have a Robot class with a talk() method that prints a message to the console.

Implementing Methods Outside the Class

To keep the class definition clean, methods are usually implemented outside the class using the scope resolution operator ::.

Here's an example:

#include <iostream>

class Robot {
public:
    void talk();
};

void Robot::talk() {
    std::cout << "Hello, I am a robot!" << std::endl;  // Output: Hello, I am a robot!
}

In this example, the talk() method is declared inside the class but implemented outside, keeping the definition simpler.

Example Code Walkthrough: Part 1

You can also add parameters to the methods. Let's create a Calculator class with a method to add numbers.

#include <iostream>

class Calculator {
public:
    // Method to add two numbers
    int add(int a, int b) {
        return a + b;
    }
};

In this code, we define a Calculator class with an add method.

Example Code Walkthrough: Part 2

Let's add more functionality to the Calculator class by including a subtract method.

#include <iostream>

class Calculator {
public:
    // Method to add two numbers
    int add(int a, int b) {
        return a + b;
    }

    // Method to subtract two numbers
    int subtract(int a, int b) {
        return a - b;
    }
};
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal