In this article member function in c++ we give the information about member functions are functions that are declared within the class definition and act on the data members of the class.
Member Function in C++:
In C++, member functions are functions that are declared within the class definition and act on the data members of the class.
Member functions have their own definition and can be defined inside or outside the class definition.
Member functions can be defined directly within the class definition. But if we define it outside the class then we have to use scope resolution operator :: with class name and function name.
In the example given below, we have defined the function inside the class.
In the example below, we have defined the function outside the class. So for this we use scope resolution operator :: :-
// member function defined outside class definition
int Square :: getResult()
Calling member functions –
Just as we access the data members of the class, similarly we can access the member function with the object using the dot operator (.)
Types of Member function in C++
It has the following types:-
- Simple functions
- Static functions
- const functions
- Inline functions
- Friend functions
Simple member function
These are basic member functions and they do not have any special keywords.
Its syntax is given below:-
Static member function –
The static keyword is used to make a function static. The member function of the class does not depend on the objects of the class.
const member function –
For this use const keyword. When a member function is declared as const then these objects can never change.
void fun() const
The inline function in c++ reduces the overhead of function calls. For this the inline keyword is used.
Through Friend functions, we can access private and protected data members of the class. For this the friend keyword is used.
// Swapping two numbers using Class
int num1, num2; // data members
void getdata() // Member functions – Inside definition
cout<<“\n\n\n Enter the 2 numbers: “;
void display(); // Member function – Outside definition
cout<<“\n Before swap Num1: “<<num1<<“\t Num2: “<<num2;
cout<<“\n After swap Num1: “<<num1<<“\t Num2: “<<num2;
swap p; // create object
p.getdata(); // calling data member using object with dot operator
Enter the 2 numbers: 10
Before swap Num1: 10 Num2: 20
After swap Num1: 20 Num2: 10