Topic 49 of 83
Class Methods
Overview
Methods can be defined directly inside the class (automatically made inline), or declared inside and defined outside using the Scope Resolution Operator `::`. This keeps class definitions clean.
Syntax
cpp
class Math {
public:
// Defined inside
int add(int a, int b) { return a + b; }
// Declared inside
int multiply(int a, int b);
};
// Defined outside using ClassName::
int Math::multiply(int a, int b) {
return a * b;
}Common Pitfalls
- Forgetting the `ClassName::` prefix when defining outside, which accidentally creates a global function instead of a class method.
Interview Tips
- In professional codebases, class declarations go into Header files (.h or .hpp), and the outside definitions go into Source files (.cpp). This speeds up compilation times significantly.
Real-World Example
Defining a complex method outside the class for readability.
example
cpp
#include <iostream>
using namespace std;
class User {
public:
string name;
void printDetails(); // Prototype
};
// Clean outside definition
void User::printDetails() {
cout << "User details processing..." << endl;
cout << "Name: " << name << endl;
}
int main() {
User u;
u.name = "Alice";
u.printDetails();
return 0;
}