C++ Class Methods
Functions that operate on class data
⚙️ What are Class Methods?
Class methods are functions defined inside a class that operate on the class's data. They define what actions objects can perform and how they behave.
class Calculator {
public:
int add(int a, int b) {
return a + b; // Method implementation
}
};
Calculator calc;
int result = calc.add(5, 3); // Calling method
Output:
result = 8
Types of Methods
Accessor Methods
Get values from private data
int getAge() {
return age;
}
Mutator Methods
Set or modify private data
void setAge(int newAge) {
age = newAge;
}
Utility Methods
Perform operations on data
void displayInfo() {
cout << name << endl;
}
Calculation Methods
Compute and return values
double calculateArea() {
return length * width;
}
🔹 Method Definition Inside Class
Defining methods directly inside a class keeps implementation close to the declaration, enhancing readability for small classes. This inline approach is common for simple getters, setters, or straightforward behaviors. However, for larger or more complex methods, it can clutter the class interface, making the definition harder to read and maintain compared to external definitions.
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int age;
double gpa;
// Method defined inside class
void introduce() {
cout << "Hi, I'm " << name << endl;
cout << "I'm " << age << " years old" << endl;
}
// Method with return value
string getGrade() {
if (gpa >= 3.5) return "A";
else if (gpa >= 3.0) return "B";
else if (gpa >= 2.5) return "C";
else return "D";
}
// Method with parameters
void updateGPA(double newGPA) {
gpa = newGPA;
cout << "GPA updated to: " << gpa << endl;
}
};
Class Structure:
Student class with methods:
- introduce() : void
- getGrade() : string
- updateGPA(double) : void
🔹 Method Definition Outside Class
Defining methods outside the class using the scope resolution operator separates interface from implementation. This practice results in a cleaner class header, improves code organization, and makes the class easier to read and maintain. It is especially beneficial in large projects and when method implementations are lengthy or complex.
class Circle {
public:
double radius;
// Method declarations
double calculateArea();
double calculateCircumference();
void displayInfo();
};
// Method definitions outside class
double Circle::calculateArea() {
return 3.14159 * radius * radius;
}
double Circle::calculateCircumference() {
return 2 * 3.14159 * radius;
}
void Circle::displayInfo() {
cout << "Circle with radius: " << radius << endl;
cout << "Area: " << calculateArea() << endl;
cout << "Circumference: " << calculateCircumference() << endl;
}
Benefits:
- Cleaner class interface
- Better code organization
- Easier to maintain
🔹 Complete Example with Methods
A practical class example integrates various method types to model real-world entities like a bank
account. It typically includes constructors for initialization, public methods for operations like
deposit() and withdraw(), private helper methods for internal logic, and perhaps a
destructor. This demonstrates how methods collaborate to encapsulate behavior and data securely.
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
string accountNumber;
double balance;
public:
// Constructor-like method
void initialize(string accNum, double initialBalance) {
accountNumber = accNum;
balance = initialBalance;
}
// Accessor methods (getters)
string getAccountNumber() {
return accountNumber;
}
double getBalance() {
return balance;
}
// Mutator methods with validation
void deposit(double amount) {
if (amount > 0) {
balance += amount;
cout << "Deposited: $" << amount << endl;
} else {
cout << "Invalid deposit amount!" << endl;
}
}
bool withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
cout << "Withdrawn: $" << amount << endl;
return true;
} else {
cout << "Invalid withdrawal!" << endl;
return false;
}
}
// Utility method
void displayAccountInfo() {
cout << "Account: " << accountNumber << endl;
cout << "Balance: $" << balance << endl;
}
};
int main() {
BankAccount account;
account.initialize("12345", 1000.0);
account.displayAccountInfo();
account.deposit(500.0);
account.withdraw(200.0);
account.displayAccountInfo();
return 0;
}
Output:
Account: 12345
Balance: $1000
Deposited: $500
Withdrawn: $200
Account: 12345
Balance: $1300