Member Functions
A member function is a function that belongs to a class.
Member functions describe object behavior.
class Student {
public:
void display();
};
Why Member Functions Matter
Member functions can work with the object's data.
class Counter {
private:
int value = 0;
public:
void increment() {
value++;
}
int getValue() const {
return value;
}
};
Each object has its own value.
Defining Inside the Class
Short functions are often defined inside the class.
class Calculator {
public:
int add(int a, int b) const {
return a + b;
}
};
Defining Outside the Class
You can declare the function inside the class and define it outside using ::.
class Calculator {
public:
int multiply(int a, int b) const;
};
int Calculator::multiply(int a, int b) const {
return a * b;
}
The Calculator:: part means:
This function belongs to the
Calculatorclass.
Const Member Functions
If a member function does not modify the object, mark it with const.
void display() const;
This tells the compiler and reader:
Calling this function should not change the object's state.
Member Function vs Normal Function
Normal function:
void printStudent(Student s);
Member function:
student.display();
The member function belongs to the object and can access its private data.
Viva Answer
A member function is a function declared inside a class. It defines object behavior and can access the object's data members. Member functions can be defined inside the class or outside using the scope resolution operator ::.
Quick Check
- What is a member function?
- What does
ClassName::functionNamemean? - Why mark a function
const? - How is a member function different from a normal function?