C++ Class Member Functions
Class member functions are those functions that are defined and prototyped within the class definition, just like other variables in the class. Class member functions are members of the class and can operate on any object of the class, accessing all members of the object.
Let's look at the previously defined class Box, and now we will use member functions to access the class members instead of directly accessing these members:
class Box
{
public:
double length; // Length
double breadth; // Breadth
double height; // Height
double getVolume(void);// Return volume
};
Member functions can be defined inside the class definition or separately using the scope resolution operator ::. Member functions defined inside the class definition are declared as inline even if the inline specifier is not used. So you can define the getVolume() function as follows:
class Box
{
public:
double length; // Length
double breadth; // Breadth
double height; // Height
double getVolume(void)
{
return length * breadth * height;
}
};
You can also define the function outside the class using the scope resolution operator :: as shown below:
double Box::getVolume(void)
{
return length * breadth * height;
}
It is important to note that the class name must be used before the :: operator. Calling a member function is done using the dot operator (.) on the object, allowing it to operate on the data related to that object, as shown below:
Box myBox; // Create an object
myBox.getVolume(); // Call the member function on the object
Let's use the concepts mentioned above to set and get the values of different members in the class:
Example
#include <iostream>
using namespace std;
class Box
{
public:
double length; // Length
double breadth; // Breadth
double height; // Height
// Member function declarations
double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};
// Member function definitions
double Box::getVolume(void)
{
return length * breadth * height;
}
void Box::setLength( double len )
{
length = len;
}
void Box::setBreadth( double bre )
{
breadth = bre;
}
void Box::setHeight( double hei )
{
height = hei;
}
// Main function of the program
int main( )
{
Box Box1; // Declare Box1, type Box
Box Box2; // Declare Box2, type Box
double volume = 0.0; // Store volume
// Box 1 details
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// Box 2 details
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// Volume of Box 1
volume = Box1.getVolume();
cout << "Volume of Box1: " << volume <<endl;
// Volume of Box 2
volume = Box2.getVolume();
cout << "Volume of Box2: " << volume <<endl;
return 0;
}
cout << "Volume of Box2: " << volume << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1: 210
Volume of Box2: 1560