Define a member function outside the class in C++

Hello everyone, in this tutorial, we will learn how we can define a member function outside the class in C++. A member function of a class is a function that is declared or defined within the class definition.

In this post, we are going to discuss two ways to define a member function of a class which is given below:

  • Within the class
  • Outside the class

Let’s see how a member function in C++ can be defined outside the class.

If you are not very much familiar with the working of class and object in C++, read this first: Classes and objects in CPP

C++ program to define a member function outside the class

We are going to use the Scope Resolution Operator(::) to define a function outside the class. Remember that the function must be declared inside the class. Have a look at the following program to understand the use of the scope resolution operator to define a member function outside of a class.

#include <iostream>

using namespace std;

class Square
{
  public:
    int side;
    
    int area(int side);
    int perimeter(int side);
    
};

int Square::area(int side)
{
  return side*side;
}

int Square::perimeter(int side)
{
  return 4*side;
} 

int main()
{
  //creating object of Square class
  Square s;
  
  s.side = 5;
  
  cout << "Area of a square of side "<< s.side << " is " << s.area(s.side) << "\n";
  cout << "Perimetr of a square of side " << s.side << " is " << s.perimeter(s.side) ;
 	
  return 0;
}

And, the output of the example program is:

Area of a square of side 5 is 25
Perimetr of a square of side 5 is 20

Explanation: As you can see, first we have created a class Square that has an integer variable side and member functions area() and perimeter().

We have not given the definition of the functions inside the class instead we have defined function area() and perimeter() outside the class Square using scope resolution operator as demonstrated in the above example program.

In the main() function, we have created an object of the Square class and set the side variable for this object as 4 and called the member functions area() and perimeter() which prints out the area and perimeter of the square respectively. That is 25 and 20.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *