...

/

Class Member Functions

Class Member Functions

Learn about member functions and how we can use them to access variables.

We’ve discussed classes and their data members. Now, let’s understand the member functions.

Declaring member functions

Just like data members, member functions are declared in the class declaration. We declare them like we declare all other functions, but this time, within classes.

Press + to interact
// normal function declaration
void output();
// function declared inside a class
class Student {
public:
void output(); //member function
int id;
int age;
string name;
};

Just like data members, we can create both private and public member functions. But why do we need private member functions? Why not make all the member functions public?

If we do create all the members public, we violate one of the core principles of OOP, i.e., encapsulation. Encapsulation involves bundling the data members and member functions that operate on the data within a class and restricting access to some members. By making all members public, we expose the object’s internal state, leading to a lack of control over how the data is accessed or modified. As the data can be modified from anywhere in the program, this can further lead to integrity issues or may cause bugs. For example, suppose in an elementary school management system, the student ages can only be between four and twelve years as per the rule. If the programmers are allowed to directly access the age variable, they may set the age to a number outside the allowed range by mistake. However, if they are only allowed to set the age through a method that applies range checks, the chances of ...