C++ Class Methods
Class Methods
Methods are functions that belong to the class.
There are two ways to define functions that belong to a class:
- Inside class definition
- Outside class definition
Define a Method Inside the Class
In the following example, we define a function inside the class, and we name
it "myMethod".
Note: You access methods just like you access attributes; by creating an object of
the class and using the dot syntax (.):
Inside Example
class MyClass { // The class
public:
// Access specifier
void myMethod() { // Method/function
defined inside the
class
cout << "Hello World!";
}
};
int main() {
MyClass
myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
Define a Method Outside the Class
Sometimes it is better to declare the method in the class and define it later (especially in large programs).
This is done by specifying the
name of the class, followed by the scope resolution :: operator,
followed by the name of the function:
Outside Example
class MyClass { // The class
public:
// Access specifier
void myMethod(); // Method/function
declaration
};
// Method/function definition outside the class
void
MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass
myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
Parameters
You can also pass values to methods just like regular functions. A method can also use and change the attributes of its own object.
In the example below, the accelerate() method adds a value to the speed attribute of the car:
Example
class Car {
public:
int speed = 0; // Attribute
void accelerate(int amount) { // Method with a parameter
speed += amount;
}
};
int main() {
Car myCar;
myCar.accelerate(50);
myCar.accelerate(30);
cout << myCar.speed; // 80
return 0;
}
Try it Yourself »
Each time accelerate() is called, it changes the speed of myCar. This is the main idea of objects: they hold data (attributes), and functions (methods) that work on that data.
Challenge Task
Create a class Dog with a method
bark() that prints "Woof!".
Then call that method from main() using an object of the class.
#include <iostream>
using namespace std;
class Dog {
public:
void bark() {
cout << "Woof!";
}
};
int main() {
Dog myDog;
myDog.bark();
return 0;
}
Try it Yourself »