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

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 day ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago