Class Member Functions

A member function of a class can be defined as a function that has its own set of definitions or its prototype defined inside the class definition. This tupe of function operates on any object of the class of which it is a member, and can freely access all the members of a class for that object.

For example:

class Car {
   public:
      double length;         // Length of a Car
      double breadth;        // Breadth of a Car
      double getArea(void);// Returns Car Area
};

Member functions are usually defined within the class definition or they can also be defined separately by using the scope resolution operator, : . Defining a member function within the class definition enables us to declare the function inline, even if we avoid using the inline specifier.

class Car {
   public:
      double length;      // Length of a Car
      double breadth;     // Breadth of a Car
         
      double getArea(void) {
         return length * breadth;
      }
};

This is one way of declaring the member function. Alternatively, we can also declare the function outside the class by using the scope operator.

For example:

float Car::getArea(void) {
   return length * breadth;
}

In this example, the only important point that we have to take into consideration is that we would have to use class name just before the :: operator. A member function will be called using a dot operator (.) on an object where it will be used to manipulate data which is related to that object. For example:

Car myCar;          // Creates an object

myCar.getArea();  // Calls member function for the object

Now we will look at the following example to understand how all the above concepts come together in perfect harmony.

#include <iostream>

using namespace std;

class Car {
   public:
      float length;         // Length of the car
      float breadth;        // Breadth of the car
      
      // Declaring Member functions
      float getArea(void);
      void setLength( double l );
      void setBreadth( double b );
};

// Defining Member functions 
float Car::getArea(void) {
   return length * breadth;
}

void Car::setLength( float l ) {
   length = l;
}
void Car::setBreadth( float b ) {
   breadth = b;
}

// Main function for the program
int main() {
   Car Car1;                // Declaring Car1 of type Car
   Car Car2;                // Declaring Car2 of type Car
   float Area = 0.0;     // Store the Area of a Car here
 
   // Car 1 specification
   Car1.setLength(3.0); 
   Car1.setBreadth(5.0); 

   // Car 2 specification
   Car2.setLength(10.0); 
   Car2.setBreadth(9.0); 

   // Area of Car 1
   Area = Car1.getArea();
   cout << "Area of Car1 : " << Area <<endl;

   // Area of Car 2
   Area = Car2.getArea();
   cout << "Area of Car2 : " << Area <<endl;
   return 0;
}:

Output:

Volume of Box1 : 15
Volume of Box2 : 90