Class Methods
C++ Class Methods
Definition: Methods are functions that are defined inside a class. They represent the "behaviors" or actions that an object can perform. While attributes store the data, methods provide the logic to manipulate or display that data.
Why: Class methods are a core part of the C++ syllabus because they implement the principle of encapsulation. By keeping functions and data together in the same block, you create self-contained objects that are easier to understand and debug.
Inside vs. Outside Definition
In C++, there are two ways to define a method belonging to a class. Both achieve the same result but are used for different levels of code organization:
Inside Class
The function is defined directly within the class braces. This is common for short, simple functions.
Outside Class
The function is declared in the class but defined later using the Scope Resolution Operator (::). This keeps the class blueprint clean.
Example: Implementing a Display Method
In this example, the show() method belongs to the Student class. We call it using the object s1 and the dot operator:
#include <iostream> using namespace std; class Student { public: // Method defined inside the class void show() { cout << "Student details displayed." << endl; } }; int main() { Student s1; // Create object // Call the class method s1.show(); return 0; }
Key Notes
- Accessing Attributes: Methods have direct access to all attributes (variables) within the same class, even if those attributes are private.
- The
thisPointer: Inside every class method, there is an implicit pointer calledthiswhich refers to the specific object that called the method. - Parameters in Methods: Just like regular functions, class methods can accept parameters. For example:
void setAge(int a) { age = a; }. - Memory Efficiency: Even if you create 100 objects of a class, the system only stores one copy of the class methods in memory, which all objects share to save space.
🏋️ Test Yourself With Exercises
Take our quiz on Class Methods to test your knowledge.
Browse Quizzes »