C++ Class Methods

C++ Class Methods

Methods are functions that belong to the class. They represent the actions that an object can perform.

Just like variables inside a class are called attributes, functions inside a class are called methods.

There are two ways to define functions that belong to a class:

  1. Inside class definition
  2. Outside class definition

1. Inside Class Definition

You can define the method directly inside the class body. This is useful for short, simple methods.

Inside Definition Example

#include <iostream>
using namespace std;

class MyClass { public: // Method/function defined inside the class void myMethod() { cout << "Hello World!"; } };

int main() { MyClass myObj; // Create an object of MyClass myObj.myMethod(); // Call the method return 0; }

To call a method, you use the object name followed by a dot (.), just like you do with attributes.


2. Outside Class Definition

For longer methods, it is better practice to declare the method inside the class and define it outside. This keeps your class definition clean and easy to read.

To define a method outside the class, you must specify the name of the class, followed by the scope resolution operator ::, followed by the name of the function.

Outside Definition Example

#include <iostream>
using namespace std;

class MyClass { public: void myMethod(); // Method declaration };

// Method definition outside the class void MyClass::myMethod() { cout << "Hello World from outside!"; }

int main() { MyClass myObj; myObj.myMethod(); return 0; }


3. Methods with Parameters

Just like regular functions, class methods can accept parameters to make them more dynamic.

Parameters Example

#include <iostream>
using namespace std;

class Car { public: int speed(int maxSpeed); // Declaration with parameter };

int Car::speed(int maxSpeed) { return maxSpeed; }

int main() { Car myObj; cout << "The car's maximum speed is: " << myObj.speed(200) << " mph\n"; return 0; }


Exercise

?

Which operator is used to define a class method outside the class definition?