Member Function In C++ - C++ Programming Tutorial
C++ Course / Functions / Member Function In C++

Member Function In C++

BLUF: Mastering Member Function In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Member Function In C++

C++ is renowned for its efficiency. Learn how Member Function In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, a member method is a function that is declared within a class and is linked to the instances of that class. It grants access to the class attributes and can interact with them directly. These methods determine the behavior of the instances and can be called upon using the instance name and dot operator.

Member functions are capable of being declared within or outside the class using the scope resolution operator. They are essential for modifying or accessing object data. These functions can have public, private, or protected access, determined by 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 a member function is declared within a class, it can be defined directly within the class itself. Otherwise, the member function needs to be defined outside the class using the scope resolution operator (::) in C++.

Syntax

It has the following syntax:

Example

returnType ClassName::functionName(parameters) {

    // Function body here

}

C++ Simple Member Function Example

Let's consider an example to demonstrate 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 illustration, we introduce a Dice class that symbolizes a three-dimensional entity with measurements for length, width, and height. Subsequently, it contains methods to establish these measurements and compute the total volume. Within the main function, two instances of the dice (Dice1 and Dice2) are instantiated. Their measurements are defined via setter methods, and their volumes are computed and displayed by invoking the getVolume function.

Defining Member Function

There are primarily two methods to declare a member function in C++.

  • Defining Member Function Within the Class
  • Implementing Member Function Outside the Class

Next, we will explore each of these member function declarations individually.

Member Function Inside the Class

In C++, we have the ability to declare member functions within a class. This enables us to interact with data members and other class functions. Essentially, member functions can be viewed as functions that are defined within the class itself. These functions are associated with a particular class or object, facilitating the manipulation of the class's data members and enabling communication with the internal state of the object or with other instances of the same class.

When defining a member function within a class, it is possible to incorporate both the function's signature and its implementation directly inside the class declaration.

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's consider an illustration to demonstrate the member function within a 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 instance, we establish an Employee class containing confidential attributes (id, name, and salary). The public methods are configured to assign and exhibit the employee information. Subsequently, the setDetails method populates the employee's data, and displayEmployee showcases it on the screen. Within the main routine, a new instance called emp1 is generated, its particulars are defined, and the information is displayed.

Member function Outside the Class

In C++, a method can be declared outside the class by employing the scope resolution operator (::) positioned before the function's identifier. The function should be named with the class name preceding the scope resolution operator. Such methods enjoy access to all class members, encompassing 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's consider an example to demonstrate defining a 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 instance, a class named Car is established containing private attributes such as brandname and modelno. Public member methods are employed to assign values to these attributes and exhibit them. Following this, the setDetails method is responsible for setting the brand and model number of the vehicle, while showDetails is tasked with showcasing this information. Within the main function, an instance of the Car class is instantiated to display the car's specifics.

Types of Member Function

There are primarily five categories of member functions in C++.

Next, we will examine each of these member functions individually.

1) Simple Member Function

In C++, standard member functions are the most frequently utilized type of member functions. These functions can be declared inside the class definition and are able to interact with the class's data members and other 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 marked as static by adding the static keyword before the function name. When a member function is defined as static, a single instance of the function is generated and shared among all instances of the class. Such functions are accessible without the need to instantiate 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's consider an example to illustrate the concept of a static member function in the C++ programming language.

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 instance, we are examining a class named Employee which includes a static data field named total. This field is responsible for maintaining a count of all the instances of Employee objects that have been created. Upon instantiation of an Employee object, the constructor will increment this total value. Within the main function, the total value is incremented universally and remains consistent across all objects.

3) Constant Member Function

In C++, a constant member function is a member function that does not alter any data members of the class. By using the const keyword, we can specify the member function as constant after the function declaration. This particular member function enables us to view the data members of an object but prohibits any modifications to them.

Syntax

It has the following syntax:

Example

return_type function_name () const

{

     //function body

}

C++ Constant Member Function Example

Let's consider an example to demonstrate the unchanging 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 instance, we are presenting a Car class that holds three private attributes: carname, carmodel, and car_color. Subsequently, the constructor sets these attributes using an initialization list. The show method is a member function marked as constant, indicating it does not modify any attributes. Within the main function, an instance c is instantiated, and its details are exhibited using the show method.

4) Inline Member Function

In C++, an inline function is a function that gets defined with the inline keyword. Within the inline function, the compiler substitutes the function call with the actual code of the function at compile time. This technique can minimize the function call overhead and enhance performance, especially for small, frequently invoked functions.

Syntax

It has the following syntax:

Example

inline return_type function_name(parameters)

{

   // Function Code    

}

C++ Inline Member Function Example

Let's consider a scenario to demonstrate 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 instance, we establish a Cuboid class containing three inaccessible attributes: length, width, and height. Subsequently, we employ a constructor to set these measurements. Within the class, two internal member functions are declared: volume and display. Within the main function, we instantiate an object c with dimensions 12, 4, and 7, and exhibit its particulars using the display function.

5) Friend Member Function

In C++, friend functions are implemented external to the class declaration and specified within the class utilizing the friend keyword. These functions, although not part of the class, possess the capability to interact with the private and protected members of the class. By declaring a function as a friend, a class can grant it specific access permissions, facilitating its manipulation of 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's consider an instance to demonstrate the friend member function scenario 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 instance, we are demonstrating a scenario where a class Student is defined, encompassing private attributes such as name, age, and marks. Subsequently, a constructor is employed to set up these attributes. The showStudetails function is then designated as a friend of the class. Within the main function, an instance of the Student class is instantiated and provided to the friend function for displaying the particulars.

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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience