Member Function In C++

In C++, a member function is a function that is defined inside a class and is associated with the objects of that class. It provides access to the class members and can operate and manipulate them directly. These functions define the objects behaviour and can be invoked using the object name and dot operator.

Member functions can be defined inside or outside the class via the scope resolution operator and are used to manipulate or retrieve object data. These functions can be public, private, or protected, depending on the access specifier .

Syntax

It has the following syntax:

Example

class Class_name {

public:

    returnType functionName(parameters);  // Declaration

};

In this syntax,

  • Class_name: It represents the class name.
  • public: It represents an access specifier.
  • returnType: It represents the value type that the function returns.
  • functionName: It represents the function name.
  • parameters: It represents the input values that the function takes.

If we define the member function inside the class, it can be defined directly inside the class. Otherwise, we have to use the scope resolution operator(::) to declare the member function in C++ outside the class.

Syntax

It has the following syntax:

Example

returnType ClassName::functionName(parameters) {

    // Function body here

}

C++ Simple Member Function Example

Let us take an example to illustrate the member function in C++.

Example

Example

#include <iostream>  

  using namespace std;   //using standard namespace

  

class Dice {  

   public:  

      double L;    // a dice's length  

      double B;   // a dice's breadth  

      double H;  // a dice's height  

  

      // Member functions declaration  

      double getVolume(void);  

      void setL(double length);  

      void setB(double breadth);  

      void setH(double height);  

};  

  

// Member functions definitions  

double Dice::getVolume(void) {  

   return L * B * H;  

}  

  void Dice::setL(double length)   

{  

   L = length;  

}  

void Dice::setB(double breadth) {  

   B = breadth;  

}  

void Dice::setH(double height) {  

   H = height;  

}    

int main() {   // Main function  

   Dice Dice1;    // Declare Dice1 of type Dice  

   Dice Dice2;    // Declare Dice2 of type Dice  

   double volume = 0.0;     // here the volume of a Dice is stored  

   

   // dice 1 specification  

   Dice1.setL(6.0);   

   Dice1.setB(7.0);   

   Dice1.setH(5.0); 

      // Dice 2 specification  

   Dice2.setL(12.0);   

   Dice2.setB(13.0);   

   Dice2.setH(10.0);  

  

   // volume of Dice 1  

   volume = Dice1.getVolume();  

   cout << "Volume of Dice1 : " << volume <<endl;  

  

   // volume ofDice 2  

   volume = Dice2.getVolume();  

   cout << "Volume of Dice2 : " << volume <<endl;  

   return 0;  

}

Output:

Output

Volume of Dice1 : 210

Volume of Dice2 : 1560

Explanation

In this example, we define a Dice class that represents a 3D object with length, breadth, and height. After that, it includes member functions to set these dimensions and calculate the volume. In the main function, two dice objects (Dice1 and Dice2) are created, their dimensions are set using setter functions, and their volumes are calculated and printed using the getVolume function.

Defining Member Function

There are mainly two ways to define a member function in C++.

  • Member Function Inside the Class
  • Member Function Outside the Class

Now, we will discuss these declarations of member functions one by one.

Member Function Inside the Class

In C++, we can define member functions inside a class. It can allow us to access data members and other member functions. It can be considered as an inline function. Member functions are belonging to a specific class or object and are used to operate on that data members of the class, allowing interaction with and manipulation of the object's internal state or with other objects of the same class.

If we want to define a member function inside a class, we can include the function's signature and implementation within the class definition.

Syntax

It has the following syntax:

Example

class ClassName {

public:

void functionName() {

// body of the function

}

};

C++ Example for Member Function Inside the Class

Let us take an example to illustrate the member function inside the class in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Employee //class definition

{

    // member variables

    int id;

    string name;

    int salary;

    

    public:  //Access Specifiers

    // member function declared and defined inside the class

    void displayEmployee()

    {

        cout << "Name: " << name << endl;

        cout << "ID: " << id << endl;

        cout << "Salary: " << salary << endl;

    }

    

    void setDetails(int empID, string empName, int empSalary){

        id = empID;

        name = empName;

        salary = empSalary;

    }

};

int main()  //Main Function

{

    Employee emp1;

    

    emp1.setDetails(101, "Alice", 50000);

    emp1.displayEmployee();

}

Output:

Output

Name: Alice

ID: 101

Salary: 50000

Explanation

In this example, we define an Employee class with private data members (id, name, and salary). We also initialize the public member functions to set and show the employee details. After that, the setDetails function initializes the data of the employee, while displayEmployee prints it to the console. In the main function, an Employee object emp1 is created, its details are set, and then the output is printed.

Member function Outside the Class

In C++, we can define the member function outside the class using the scope resolution operator (::) that is placed before the function name. The function name needs to include the class name followed by the scope resolution operator. These member functions have access to all members of the class, such as public, private, and protected members.

Syntax

It has the following syntax:

Example

class Class_name {

public:  //Access Modifiers

    returnType function_name(parameters);  // Function declaration

};

// Function definition outside the class

returnType ClassName::functionName(parameters) {

    // body of the function

}

C++ Example for Member Function Outside the Class

Let us take an example to illustrate the member function outside the class.

Example

Example

#include <iostream>

using namespace std;  // using standard namespace 

class Car {

private:

    string brand_name;

    int model_no;

public:

    void setDetails(string name, int model); // Combined setter

    void showDetails();      // Display function

};

// Definitions outside the class

void Car::setDetails(string name, int model) {

    brand_name = name;

    model_no = model;

}

void Car::showDetails() {

    cout << "Car Name: " << brand_name << endl;

    cout << "Car Model: " << model_no << endl;

}

int main() {  // Main Function

    Car c;

    c.setDetails("BMW", 2025);  

    c.showDetails(); 

    return 0;

}

Output:

Output

Car Name: BMW

Car Model: 2025

Explanation

In this example, we define a Car class with private data members brandname and modelno. We also use public member functions to set and display these details. After that, the setDetails function initializes the brand and model no of the car, while showDetails prints their details. In the main function, a Car object is created that presents the information of the car.

Types of Member Function

There are mainly five types of member functions in C++.

Now, we will discuss these member functions one by one.

1) Simple Member Function

In C++, normal member functions are the commonly used type of member functions. We can define these functions within the class definition, and can have access to the data members and other class member functions.

Syntax

It has the following syntax:

Example

return_type functionName(parameter_list)

{

    function body;

}

2) Static Member Function

In C++, a function can be defined as static using a static keyword with the function name. If we declare a member function as static, only one copy of the function is created and utilized by all the class objects. These functions can be invoked without creating a class object.

Syntax

It has the following syntax:

Example

class Class_name {

public:  //Access Modifier

    static return_type FunctionName(parameters);

};

C++ Static Member Function Example

Let us take an example to demonstrate the static member function in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Employee {

public:

	// static member

	static int total;

	// Constructor called

	Employee() { total += 1; }

};

int Employee::total = 0;

int main()  //Main Function

{

	//Employee Declaration

	Employee emp1;

	cout << "Employee No: " << emp1.total << endl;

	Employee emp2;

	cout << "Employee No: " << emp2.total << endl;

	Employee emp3;

	cout << "Employee No: " << emp3.total << endl;

	return 0;

}

Output:

Output

Employee No: 1

Employee No: 2

Employee No: 3

Explanation

In this example, we have taken a class Employee that contains a static data member total. It keeps track of the total number of employee objects created. When an Employee object is instantiated, the constructor increments the total. In the main function, the value of the total increases globally and is the same for every object.

3) Constant Member Function

In C++, a constant member function is a member function that will not change any data members of the class. Using the const keyword , we can declare the member function after the function declaration. This member function allows us to access the data members of an object but cannot modifying them.

Syntax

It has the following syntax:

Example

return_type function_name () const

{

     //function body

}

C++ Constant Member Function Example

Let us take an example to illustrate the constant member function in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Car {

private:

    string car_name;

    int car_model;

    string car_color;

public:

    Car(string n, int m, string c) : car_name(n), car_model(m), car_color(c) {}

    // Constant member function

    void show() const {

        cout << "Car Name: " << car_name << ", Model: " << car_model << ", Color: " << car_color << endl;

    }

};

int main() { //Main Function

    Car c("BMW", 2020, "Black");

    c.show();  

    return 0;

}

Output:

Output

Car Name: BMW, Model: 2020, Color: Black

Explanation

In this example, we have taken a Car class that contains three private data members: carname, carmodel, and car_color. After that, the constructor initializes these members using an initialization list. The show function is a constant member function, which means that it does not change any data members. In the main function, an object c is created, and the show function displays its details.

4) Inline Member Function

In C++, an inline function is a function that is defined using the inline keyword. In the inline function, a compiler replaces the function call with the original code of the function during compile time. It can help to reduce the function call overhead and improve the performance, particularly for small and frequently used functions.

Syntax

It has the following syntax:

Example

inline return_type function_name(parameters)

{

   // Function Code    

}

C++ Inline Member Function Example

Let us take an example to illustrate the inline member function in C++.

Example

Example

#include <iostream>

using namespace std; //using standard namespace

class Cuboid {  

private:

    int length;

    int width;

    int height;

public:

    // Constructor with initialization list

    Cuboid(int l, int w, int h) : length(l), width(w), height(h) {}

    // Inline member function defined inside the class

    int volume() {

        return length * width * height;

    }

    // Inline member function defined inside the class

    void show() {

        cout << "Length: " << length << endl; 

        cout << "Width: " << width << endl; 

        cout << "Height: " << height << endl; 

        cout << "Volume of the Cuboid: " << volume() << endl; 

    }

};

int main() {  //Main Function

    Cuboid c(12, 4 , 7);

    c.show();  //prints the output

    return 0;

}

Output:

Output

Length: 12

Width: 4

Height: 7

Volume of the Cuboid: 336

Explanation

In this example, we define a Cuboid class with three private members: length, width, and height. After that, it uses a constructor to initialize these dimensions. Two inline member functions are defined inside the class: volume and show. In the main function, an object c is created with dimensions 12, 4, and 7, and its details are printed using the show function.

5) Friend Member Function

In C++, friend functions are defined outside the class definition and declared inside the class using the friend keyword. Friend functions are non-member functions that have access to the private and protected members of the class. If we want to declare a function as a friend function, a class can allow it special access privileges, which enables it to work on the class's internal data.

Syntax

It has the following syntax:

Example

class class_name

{

 friend data_type function_name(arguments);  //Friend Function Declaration  

};

C++ Friend Member Function Example

Let us take an example to illustrate the friend member function example in C++.

Example

Example

#include <iostream>

using namespace std;  //using standard namespace

class Student {

private:

    string name;

    int age;

    int marks;

public:

    // Constructor to initialize the student details

    Student(string n, int a, int m) : name(n), age(a), marks(m) {}

    // Friend function declaration

    friend void showStudetails(Student &s);

};

// Friend function definition

void showStudetails(Student &s) {

    cout << "Student Name: " << s.name << endl;

    cout << "Age: " << s.age << endl;

    cout << "Marks: " << s.marks << endl;

}

int main() {  //Main Function

    // Creating a Student object

    Student student("Alice", 24, 75);

    // call friend function to show details

    showStudetails(student);

    return 0;

}

Output:

Output

Student Name: Alice

Age: 24

Marks: 75

Explanation

In this example, we have taken a class Student that contains private data members: name, age, and marks. After that, a constructor is used to initialize these data members. The function showStudetails is declared as a friend of the class. In the main function, a Student object is created and passed to the friend function to show the details.

C++ Member Function MCQs

1) Which of the following options shows the memory function in C++?

  • A global function
  • A function declared inside a namespace
  • A function declared inside a class
  • A function in the main function

2) What is the correct syntax to define a member function in C++?

  • className::functionName
  • return_type ClassName::functionName
  • return_type ClassName.functionName
  • return_type functionName

3) Which of the following options is not a valid type of member function?

  • Mutable
  • Inline
  • Static
  • Const

4) Which of the following options is correct for static member functions in C++?

  • They can access only non-static members
  • They should be private
  • They are invoked using objects only
  • They cannot access this pointer

5) Which of the following keywords is used to define a static member function in C++?

  • const
  • friend
  • static
  • inline

Input Required

This code uses input(). Please provide values below: