A member function is a function that is declared as a class member. It is declared within the class in any of the visibility modes, i.e. public, private, or protected, and it has access to all the class’s data members. If the member function is defined within the class definition, it can be defined directly within the class; otherwise, we must declare the member function in C++ outside the class using the scope resolution operator (::). (we will see about it later in the article).
Note: The main goal of using the member function is to add modularity to a program, which is commonly used to improve code reusability and maintainability.
For example:
class Rectangle {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double getArea(void);// Returns box area
};
Member functions can be defined either within the class definition or independently using the scope resolution operator,:- Even if you do not use the inline specifier, defining a member function within the class definition declares the function inline. Alternatively, you can define the Area() function as shown below.
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double getArea(void) {
return length * breadth ;
}
};
Otherwise, one can define the same function outside the class using the scope resolution operator (::) as follows −
double Box::double getArea(void) {
return length * breadth ;
}
Calling Class Member Function:
Similar to accessing a data member in the class, we can use the dot operator to access the public member functions via the class object (.).
For instance,
int main()
{
Box obj1;
obj1.length = 4.7;
obj1.breadth = 2.3;
cout<< "Area of Box = "<< obj1.getArea();
}
Note: also read about Accessing data members
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment