Class Methods
Overview
Functions that are written inside a Class are specifically called Methods. Methods represent the 'Behavior' of an object (e.g., a Dog object has a bark() method).
In massive enterprise projects, writing all the logic directly inside the Class definition (in the .h header file) makes the file thousands of lines long and impossible to read. C++ elegantly solves this by allowing developers to declare the Method inside the Class, but physically define the logic outside the Class (usually in a separate .cpp file) using the Scope Resolution Operator (`::`).
Syntax
// --- 1. INSIDE THE CLASS (Header File style) ---
class Calculator {
public:
// Declaration ONLY (The signature)
int add(int a, int b);
};
// --- 2. OUTSIDE THE CLASS (CPP File style) ---
// We use ClassName::MethodName to tell the compiler exactly
// which class this function belongs to!
int Calculator::add(int a, int b) {
return a + b;
}
int main() {
Calculator calc;
std::cout << calc.add(5, 5) << "\n"; // 10
return 0;
}Common Pitfalls
- Forgetting the
ClassName::prefix when defining outside the class. If you just writeint add(int a, int b) { ... }, the compiler thinks you are creating a brand new, global standalone function. When you try to callcalc.add(), it will crash saying the method is undefined.
Interview Questions
::?Methods defined entirely inside the class are implicitly marked as inline by the compiler. The compiler will attempt to copy-and-paste their machine code directly into the caller's block to save execution time. Methods defined outside the class using :: are treated as standard functions with normal jump overhead.
Real-World Example
Cleanly organizing code by separating the 'What it does' (Declaration) from the 'How it does it' (Definition).
#include <iostream>
#include <string>
class Player {
public:
std::string name;
void attack(); // Clean, readable blueprint
};
// The messy logic is hidden down here (or in another file!)
void Player::attack() {
std::cout << name << " swings their sword for 50 damage!\n";
}
int main() {
Player p;
p.name = "Arthur";
p.attack();
return 0;
}Check Your Knowledge
Test your understanding of Class Methods with these quick questions.