Methods (Member Functions)
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 8 of 104.
Member functions define what an object can do. They have a return type, a name, and optional parameters.
Method returning a value
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};Void method (no return value)
class Printer {
public:
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
};Method returning bool
class Checker {
public:
bool isPositive(int num) {
return num > 0;
}
};Declaring in header, implementing in source
// Calculator.h
class Calculator {
public:
int add(int a, int b);
};
// Calculator.cpp
int Calculator::add(int a, int b) {
return a + b;
}The return type goes before the method name. Use void when a method doesn't return anything. The :: scope resolution operator links implementations to their class.
Challenge
MediumImplement four member functions for the StringHelper class with different return types and parameters:
getLength()— returnsint, the length of texttoUpperCase()— returnsstd::string, text in uppercasecontains(std::string word)— returnsbool, whether text contains the wordrepeat(int times)— returnsstd::string, text repeated with spaces
Cheat sheet
Member functions define what an object can do. They have a return type, a name, and optional parameters.
Method returning a value:
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
};Void method (no return value):
class Printer {
public:
void printMessage(std::string msg) {
std::cout << msg << std::endl;
}
};Method returning bool:
class Checker {
public:
bool isPositive(int num) {
return num > 0;
}
};Declaring in header, implementing in source:
// Calculator.h
class Calculator {
public:
int add(int a, int b);
};
// Calculator.cpp
int Calculator::add(int a, int b) {
return a + b;
}The return type goes before the method name. Use void when a method doesn't return anything. The :: scope resolution operator links implementations to their class.
Try it yourself
#include <iostream>
#include "StringHelper.h"
int main() {
std::string input;
std::getline(std::cin, input);
StringHelper helper;
helper.text = input;
std::cout << "Original: " << helper.text << std::endl;
std::cout << "Length: " << helper.getLength() << std::endl;
std::cout << "Uppercase: " << helper.toUpperCase() << std::endl;
std::cout << "Contains 'World': " << (helper.contains("World") ? "yes" : "no") << std::endl;
std::cout << "Repeated: " << helper.repeat(3) << std::endl;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container