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 ;
}
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
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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…