Member functions
- C++ course
- Intermediate
- Lesson 3/116
- 5 min
Learn to define member functions (methods) in a class.
Member functions
Functions declared in a class body are called member functions. They define the object's behavior. In a Counter class, void increment() { count++; } is a member function.
Member functions can access other members of the class directly: you just write count, no need for this->count. Calls use a dot: counter.increment();. Member functions defined inside the class body are treated as inline.
Return value and parameters
Member functions can return a value and take parameters, just like free functions. Example: int add(int x) { return count + x; }. Here int is the return type and x is a parameter.
A void function returns no value; return is omitted or used only to end the flow. Functions that return a value must have a return statement in their body. You can assign the returned value to a variable or print it directly.
Practice Add a member function to the Counter class
Define a Counter class. Under public: add int count; and the member function void increment() { count++; }. In main create an instance, call increment and print count with std::cout.
Starter code
#include <iostream>
// Define the Counter class here
int main() {
// Create a Counter instance, call increment and print count
return 0;
}Sample solution
#include <iostream>
class Counter {
public:
int count;
void increment() {
count++;
}
};
int main() {
Counter counter;
counter.count = 0;
counter.increment();
std::cout << counter.count;
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
void increment() |
Member function declaration |
counter.increment() |
Member function call |
int count; |
Member variable |
class Counter { }; |
Class definition |
2 Complete the return statement
int getValue() { ____ value; }
int getValue() { return value; }
Explanation: return sends the value back.
3 What does counter.increment(); do?
Counter counter;- Redefines the class
- Deletes a member variable Correct answer
- Calls the increment member function
- Creates a new instance
Explanation: The dot calls a member function.