...

/

Class Member Functions

Class Member Functions

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

We’ve looked at classes and their data members. Now, let’s have a look at 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 DayOfYear {
public:
void output(); //member function
int month;
int day;
};

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 maybe cause bugs.

That's why we use setters and getters.

Setters and Getters

As we know private member variables cannot be accessed directly in any ...