← Back to C++ Course | Chapter 8: OOP Core | Lesson 3 of 14

C++ Class Methods

A class method (member function) is a function declared inside a class that operates on that class's objects, defined either inline within the class body or separately using the scope resolution operator.

What is a Class Method?

A class method, also called a member function, is a function declared as part of a class, and every object of that class can call it, giving the method automatic access to that specific object's data.

Example: What is a Class Method?

cpp
#include <iostream>

class Greeter {
public:
	void greet() { std::cout << "Hello!" << std::endl; }
};

int main() {
	Greeter g;
	g.greet();
	return 0;
}

Defining a Method Inline

A method's body can be written directly inside the class definition, called an inline definition, which is convenient for short methods but keeps the class declaration longer.

Example: Defining a Method Inline

cpp
#include <iostream>

class Box {
public:
	int getSize() { return 10; } // defined inline, right inside the class
};

int main() {
	Box b;
	std::cout << b.getSize() << std::endl;
	return 0;
}

Defining a Method Outside the Class

A method can be declared inside the class but defined later outside it, using the class name followed by :: (the scope resolution operator) to indicate which class the definition belongs to.

Example: Defining a Method Outside the Class

cpp
#include <iostream>

class Box {
public:
	int getSize();
};

int Box::getSize() {
	return 20;
}

int main() {
	Box b;
	std::cout << b.getSize() << std::endl;
	return 0;
}

Methods that Return a Value

A method can return a value just like a regular function, computed from the calling object's own member variables, letting the object provide information about its own state.

Example: Methods that Return a Value

cpp
#include <iostream>

class Circle {
	double radius = 2.0;
public:
	double area() { return 3.14159 * radius * radius; }
};

int main() {
	Circle c;
	std::cout << c.area() << std::endl;
	return 0;
}

Methods that Take Parameters

A method can accept its own parameters in addition to having access to the object's member variables, letting it combine external input with the object's internal state.

Example: Methods that Take Parameters

cpp
#include <iostream>

class Calculator {
public:
	int add(int a, int b) { return a + b; }
};

int main() {
	Calculator calc;
	std::cout << calc.add(3, 4) << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.