Categories: C++

Member Functions of Class in C++

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

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago