C++ is one of the most effective, advanced object-oriented programming languages that gives programmers the ability to formulate complicated data types and operate on them. Classes and their member functions, which facilitate information hiding and enhance modularity, form the core of C++ programming. Every class that embraces methods enhances those methods and any method of a class is termed a member function. They are most often declared public because member functions have to be called from outside the class definition. Member functions broaden the object-oriented programming sensation as they provide guaranteed control of implementation encapsulation in addition to providing mechanisms for analysing and manipulating data stored in objects.
In this article, we will cover many aspects of C++ member function including what it is, what are its types, how it is defined, and how it is used as well as best practices along with examples to illustrate the concepts.
What are Member Functions in C++?
Functions defined inside a class that works with the data members of the class are known as member functions. Operators and functions that are declared as class members are known as member functions. They serve as an interface for the class’s users and are used to manipulate the data inside the class. Operators and functions specified with the friend specifier are not considered member functions.
Member functions can be static functions, which can be called without a class instance, or instance functions, which must call an object of the class to be invoked. Within the class scope, regardless of where the member function is defined, even if before the member’s declaration in the list of members of a class, the member function body is analysed after the class declaration to permit the use of class members within bodies of member functions.
Syntax:
class Car{
int year;
string name;
string make;
public:
string showDetails(int year);
}
In the given syntax, the showDetails() is the member function that is declared, but not defined yet. We will see detailed examples of member functions in this article.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Access Modifiers and Member Functions
The public, protected, and private access modifiers are common access modifiers used for managing who can access class members, including member functions. Here are some:
Public: Members are accessible from outside the class.
Protected: Members are only available within the class and any classes that derive from it.
Private: Access to members is limited to the class itself.
Example:
#include <iostream>
using namespace std;
class Car {
private:
string maker;
public:
void showDetails(string m) {
maker = m;
}
void display() {
cout << "Car maker is: " << maker << endl;
}
};
int main() {
Car car;
car.showDetails("BMW"); // Access public member function
car.display(); // Access public member function
return 0;
}
Explanation:
In this example, the Car class has a private member maker and two public member functions: showDetails() and display(). The showDetails() function allows external code to set the maker, while display() outputs it.
Ways to Define Member Functions in C++
Member functions can be defined in C++ in a few different ways. Your choice of approach will rely on various aspects such as performance, maintainability, and readability of the code. There are two main approaches to defining member functions:
Inside the class definition
Outside the class definition
Let’s understand these types for defining the member functions in C++ with the help of examples.
Inside the Class Definition
Member functions can be defined inside a class and can access data members and other member functions. A member function is automatically considered as an inline function when it is defined inside the class declaration. This means that to save overhead, the compiler may, in some cases, change the function code for the function call. They can be used to interact with other objects of the same class and conduct operations on the data members of the class because they are linked to a particular class or object.
Syntax:
class ClassName {
public:
void functionName() {
// Function body
}
};
Example:
#include <iostream>
using namespace std;
class Car {
// Data members
string make;
int year, mileage;
public:
// Constructor to initialise the car details.
Car(string m, int y, int mil) : make(m), year(y), mileage(mil) {}
// Member functions defined inside the class.
// Show the make of the Car.
string showMake() {
return make;
}
// Set the make of the Car.
void setMake(string m) {
make = m;
}
// Show the year of the Car.
int showYear() {
return year;
}
// Set the year of the Car.
void setYear(int y) {
year = y;
}
// Show the mileage of the Car.
int showMileage() {
return mileage;
}
// Set the mileage of the Car.
void setMileage(int mil) {
mileage = mil;
}
};
int main() {
// Define the objects of the Car class.
Car c1("BMW", 2014, 14); // Initial values: make, year, mileage
Car c2("Audi", 2018, 32);
// Access and modify car details using member functions.
c1.setYear(2015); // Update year for c1
c1.setMileage(16); // Update mileage for c1
c2.setMake("Hyundai"); // Update make for c2
c2.setYear(2020); // Update year for c2
c2.setMileage(28); // Update mileage for c2
// Display car details
cout << "Car 1 Details:" << endl;
cout << "Make: " << c1.showMake() << endl;
cout << "Year: " << c1.showYear() << endl;
cout << "Mileage: " << c1.showMileage() << endl;
cout << "nCar 2 Details:" << endl;
cout << "Make: " << c2.showMake() << endl;
cout << "Year: " << c2.showYear() << endl;
cout << "Mileage: " << c2.showMileage() << endl;
return 0;
}
<strong> </strong>
Output:
Car 1 Details:
Make: BMW
Year: 2015
Mileage: 16
Car 2 Details:
Make: Hyundai
Year: 2020
Mileage: 28
Explanation:
In this example, the constructors are initiated such as make, year, and mileage when the object is created.
The member functions such as showMake(), showYear(), and showMileage() are used to access the private data members of the class.
The setMake(), setYear(), and setMileage() functions modify the private data members.
In the main() function, we have created the two Car objects (c1 and c2) with initial values, modified their attributes using setter functions, and finally displayed the updated car details using the show functions.
Outside the Class Definition using Scope Resolution Operator
When working with large functions, it can be helpful to define member functions outside of the class to maintain a clean and understandable class definition. The scope resolution operator (::) needs to be used in the function specification in order to link the function to its class. To identify a function as a member function, its name must contain the class name, the scope resolution operator, and the function’s return type.
Syntax:
class ClassName {
public:
returnType functionName(parameterList); // Declaration inside the class
};
// Definition outside the class using scope resolution operator
returnType ClassName::functionName(parameterList) {
// Function body
}
Example:
#include <iostream>
using namespace std;
class Car {
// Data members
string make;
int year, mileage;
public:
// Constructor to initialise the car details
Car(string m, int y, int mil);
// Member function declarations
string showMake(); // Declaration only
void setMake(string m); // Declaration only
int showYear(); // Declaration only
void setYear(int y); // Declaration only
int showMileage(); // Declaration only
void setMileage(int mil); // Declaration only
};
// Definition of constructor outside the class
Car::Car(string m, int y, int mil) : make(m), year(y), mileage(mil) {}
// Member function definitions outside the class using scope resolution operator
// Show the make of the Car
string Car::showMake() {
return make;
}
// Set the make of the Car
void Car::setMake(string m) {
make = m;
}
// Show the year of the Car
int Car::showYear() {
return year;
}
// Set the year of the Car
void Car::setYear(int y) {
year = y;
}
// Show the mileage of the Car
int Car::showMileage() {
return mileage;
}
// Set the mileage of the Car
void Car::setMileage(int mil) {
mileage = mil;
}
int main() {
// Define the objects of the Car class with initial values.
Car c1("Toyota", 2014, 50000); // Initial values: make, year, mileage
Car c2("Honda", 2018, 30000);
// Access and modify car details using member functions.
c1.setYear(2015); // Update year for c1
c1.setMileage(52000); // Update mileage for c1
c2.setMake("Hyundai"); // Update make for c2
c2.setYear(2020); // Update year for c2
c2.setMileage(15000); // Update mileage for c2
// Display car details
cout << "Car 1 Details:" << endl;
cout << "Make: " << c1.showMake() << endl;
cout << "Year: " << c1.showYear() << endl;
cout << "Mileage: " << c1.showMileage() << endl;
cout << "nCar 2 Details:" << endl;
cout << "Make: " << c2.showMake() << endl;
cout << "Year: " << c2.showYear() << endl;
cout << "Mileage: " << c2.showMileage() << endl;
return 0;
}
Output:
Car 1 Details:
Make: Toyota
Year: 2015
Mileage: 52000
Car 2 Details:
Make: Hyundai
Year: 2020
Mileage: 15000
Explanation:
In this example, the data members make, year, and mileage are declared privately.
Member functions and the constructor are declared publicly inside the class but without their bodies.
The constructor Car::Car(string m, int y, int mil) initialises the data members using an initialiser list.
Car::showMake(), Car::setMake(), Car::showYear(), Car::setYear(), Car::showMileage(), and Car::setMileage() are defined outside the class using the scope resolution operator (::). These functions are now associated with the Car class.
Objects c1 and c2 are created with initial values for their attributes. The member functions are called to modify and display the car details, showcasing the correct use of the scope resolution operator.
Types of Member Functions in C++
C++ allows various types of member functions based on their accessibility and functionality. The main types include:
Instance Functions
Instance functions are also referred to as member functions and are probably the most common compared to the others. They act only on particular or non-static data members, and class instances. The following is a syntax on how to define an instance member function:
Syntax:
class ClassName {
public:
void functionName() {
// function body
}
};
Example:
#include <iostream>
#include <string>
using namespace std;
// Car Class
class Car {
private:
string brand; // Brand of the car
string model; // Model of the car
int year; // Build year
float mileage; // Mileage of the car
public:
// Constructor to initialise a Car object
Car(string b, string m, int y, float ml) : brand(b), model(m), year(y), mileage(ml) {}
// Member function to display car details
void displayDetails() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
cout << "Mileage: " << mileage << endl;
}
// Member function to update the price
void updateMileage(float newMileage) {
mileage = newMileage;
}
};
int main() {
// Create a Car object
Car car1("BMW", "M4", 2021, 10.4);
// Display initial details of the car
car1.displayDetails();
// Update the mileage of the car
car1.updateMileage(11.5);
// Display updated details of the car
car1.displayDetails();
return 0;
}
Output:
Brand: BMW
Model: M4
Year: 2021
Mileage: 10.4
Brand: BMW
Model: M4
Year: 2021
Mileage: 11.5
Explanation:
In this example, the Car class has a constructor that initialises the brand, model, year, and mileage of the car.
Some other member functions, like displayDetails() and updateMileage(float newMileage), are used to perform actions on the object.
We have used the displayDetails() that displays the car’s attributes, while updateMileage() modifies the mileage. These functions operate on a specific object of the class.
Static Functions
Static member functions are functions that can only exist in a class and which cannot be linked to any specific object. They cannot call any instance data members but only the static data members. The following is the syntax for defining a static function:
Syntax:
class ClassName {
public:
static void functionName() {
// function body
}
};
Example:
#include <iostream>
using namespace std;
// Define the Car class
class Car {
private:
static int carCount; // Static data member to keep track of the number of cars
public:
// Constructor increments carCount each time a Car object is created
Car() {
carCount++;
}
// Static member function to get the total number of cars
static int getCarCount() {
return carCount;
}
};
// Initialise static data member
int Car::carCount = 0;
int main() {
// Create multiple Car objects
Car c1;
Car c2;
Car c3;
Car c4;
Car c5;
// Call the static function using the class name
cout << "Total number of cars: " << Car::getCarCount() << endl;
return 0;
}
Output:
Total number of cars: 5
Explanation:
In this example, the static data member carCount keeps track of the number of Car objects created.
The static function getCarCount() returns the total number of cars. Because static functions are associated with the class, not objects, they are called using the class name (Car::getCarCount()).
Const Member Functions
Const member functions are likely member functions of the class that do not change any member variables of the class. They guarantee that the function will not consider any changes which will alter the condition of the object. The syntax for defining the const member function is:
Syntax:
class ClassName {
public:
void functionName() const {
// function body
}
};
Example:
#include <iostream>
#include <string>
using namespace std;
// Car Class
class Car {
private:
string brand; // Brand of the car
string model; // Model of the car
int year; // Build year
float mileage; // Mileage of the car
public:
// Constructor to initialise a Car object
Car(string b, string m, int y, float ml) : brand(b), model(m), year(y), mileage(ml) {}
// Const member function to get the car's mileage
double getMileage() const {
return mileage;
}
// Member function to display car details
void displayDetails() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
cout << "Mileage: " << mileage << endl;
}
// Non-const member function that can modify the object
void setMileage(float newMileage) {
mileage = newMileage;
}
};
int main() {
// Create a Car object
Car car1("BMW", "M4", 2021, 10.4);
// Display initial details of the car
car1.displayDetails();
// Update the mileage of the car
car1.setMileage(11.5);
// Display updated details of the car
car1.displayDetails();
return 0;
}
Output:
Brand: BMW
Model: M4
Year: 2021
Mileage: 10.4
Brand: BMW
Model: M4
Year: 2021
Mileage: 11.5
Explanation:
In the example, getMileage() is a const member function returning the car’s mileage by not altering the object.
The const here ensures that this function cannot modify any member variables, giving a guarantee to the caller about this function’s behaviour. This is especially useful when you want to provide read-only access to data.
Friend Functions
Friend functions are not member functions of a class; however, they are allowed to use the private and protected members of the class. It can be applied when you want to use a function away from the class and still make it possible to use the data members. Friend Functions are declared inside the class using a friend keyword before the return type of the function. The syntax below demonstrates how a friend function is defined:
Syntax:
class ClassName {
friend returnType functionName(parameters);
};
Example:
#include <iostream>
#include <string>
using namespace std;
// Car Class
class Car {
private:
string brand; // Brand of the car
string model; // Model of the car
int year; // Build year
float mileage; // Mileage of the car
public:
// Constructor to initialise a Car object
Car(string b, string m, int y, float ml) : brand(b), model(m), year(y), mileage(ml) {}
// Friend function to display the car's price directly
friend void showMileage(const Car& car);
};
// Friend function definition
void showMileage(const Car& car) {
cout << "The mileage of the " << car.brand << " " << car.model << " is " << car.mileage << endl;
}
int main() {
// Create a Car object
Car car1("BMW", "M4", 2021, 10.4);
// Display initial details of the car
showMileage(car1);
return 0;
}
Output:
The mileage of the BMW M4 is 10.4
Explanation:
In this example, a howMileage() is declared as a friend function that accesses the private member brand, model, and mileage of the Car object.
They are used when an external function needs access to the class’s private data, bypassing the need for getters or setters.
The car mileage has been calculated in this example using a friend function and shown in the output.
Virtual Functions
A virtual function is a member function in the base class that is redefined in a derived class in C++. It permits runtime polymorphism to the program, which means at a program execution time, one decides which function to execute based on the type of class the object is instantiated from. The syntax for defining the virtual member function is:
Syntax:
class Base {
public:
virtual void functionName() {
// base class implementation
}
};
class Derived : public Base {
public:
void functionName() override {
// derived class implementation
}
};
Example:
#include <iostream>
#include <string>
using namespace std;
// Base Car class
class Car {
public:
// Virtual function to display car information
virtual void showInfo() const {
cout << "It is a normal car." << endl;
}
// Virtual destructor
virtual ~Car() {}
};
// Derived class
class SuperCar : public Car {
private:
string brand; // Brand of the sports car
int speed; // Speed of the sports car
public:
// Constructor to initialise a SuperCar object
SuperCar(string b, int s) : brand(b), speed(s) {}
// Override the base class function
void showInfo() const override {
cout << "This car is a " << brand << " super car with a top speed of " << speed << " miles per hour." << endl;
}
};
int main() {
// Create a base class pointer to a derived class object
Car* car1 = new SuperCar("BMW", 200);
// Call the virtual function
car1->showInfo(); // Calls the derived class function
// Clean up
delete car1;
return 0;
}
Output:
This car is a BMW super car with a top speed of 200 miles per hour.
Explanation:
In this example, we have declared a virtual member function in C++.
The Car class has a virtual function showInfo(), which is overridden in the SuperCar derived class.
When a Car pointer is used to call showInfo() on a SuperCar object, the derived class’s version of showInfo() is executed, demonstrating runtime polymorphism.
The virtual destructor ensures proper cleanup in derived classes.
The speed of the car using the virtual member functions is displayed in the output.
Inline Functions
Inline functions are defined inside a class and are usually small functions that are defined to be expanded in line when they are called. This can reduce the function call overhead. The inline keyword is used to define an inline member function in C++. The following is the syntax for defining the inline functions:
Syntax:
class ClassName {
public:
inline returnType functionName(parameters) {
// function body
}
};
Example:
#include <iostream>
#include <string>
using namespace std;
// Car Base class
class Car {
private:
string name; // Name of the car
float mileage; // Mileage of the car
public:
// Constructor to initialise a Car object
Car(string n, float ml) : name(n), mileage(ml) {}
// Inline member function to get the car's name
inline string showName() const {
return name;
}
// Inline member function to get the car's price
inline double getMileage() const {
return mileage;
}
};
int main() {
// Create a Car object
Car car1("BMW", 14.6);
// Call inline functions
cout << "Name: " << car1.showName() << endl;
cout << "Mileage: " << car1.getMileage() << endl;
return 0;
}
Output:
Name: BMW
Mileage: 14.6
Explanation:
In this example, we have used the Inline functions defined with the inline keyword,
The showName() and getMileage() are inline member functions that directly return the car’s name and mileage. This can improve performance for small, frequently called functions.
The name and mileage of the car using the inline member functions are being displayed in the output.
Accessing the Private Member Function of a Class
Encapsulation prevents direct access to private member functions from outside the class, hence it is impossible to reach a class’s private member functions. The class members that are declared as private are not accessible to any class object, not even functions inside the class. But there are some ways to accomplish this indirectly, like by modifying the class to provide a public interface, or by using friend functions and friend classes.
Using Friend Functions
Friend functions have access to private members, including private member functions, as they have unique capabilities for doing all of this in C++. See the example for accessing the private member function of a class using friend functions.
Example:
#include <iostream>
using namespace std;
// Class definition
class Car {
private:
void carPrivateFunc() {
cout << "This is a Private function!" << endl;
}
public:
friend void callCarPrivateFunc(Car& obj); // friend function
};
void callCarPrivateFunc(Car& obj) {
obj.carPrivateFunc(); // Access private function
}
int main() {
Car car; // creating a car object
callCarPrivateFunc(car); // Call private function through friend
return 0;
}
Output:
This is a Private function!
Explanation:
In this example, callCarPrivateFunc() is a friend function of the Car class. It can access the private member function carPrivateFunc() and call it.
Using Friend Classes
The private and protected members of another class are accessible to a friend class. You may also use this approach to access private member functions in C++. See the example for accessing the private member function of a class using friend classes.
Example:
#include <iostream>
using namespace std;
// Class C1 definition
class C1 {
private:
void carAPrvtFunc() {
cout << "Private function in class C1 called!" << endl;
}
friend class C2; // C2 is a friend of C1
};
// Class C2 definition
class C2 {
public:
void callCarPrivateFunc(C1& c1) {
c1.carAPrvtFunc(); // Access private function of C1
}
};
int main() {
C1 c1;
C2 c2;
c2.callCarPrivateFunc(c1); // Call private function through friend class
return 0;
}
Output:
Private function in class C1 called!
Explanation:
In this example, class C2 is a friend class of C1, and can access the private function carAPrvtFunc().
Using Public Member Functions as Wrappers
Providing a public member function that invokes the private member function inside is another popular technique, and we call this wrappers. See the example for accessing the private member function of a class using the public member function as a wrapper.
Example:
#include <iostream>
using namespace std;
// Define the class
class Car {
private:
void privateFunc() {
cout << "This is a Private function!" << endl;
}
public:
void callPrivate() { // Public function acts as a wrapper
privateFunc();
}
};
int main() {
Car car;
car.callPrivate(); // Access private function through public wrapper
return 0;
}
Output:
This is a Private function!
Explanation:
In this example, the public function callPrivate() acts as a wrapper to call the private function privateFunc().
Member Function Overloading
In C++, you can have many functions with distinct argument lists but the same function name in the same class with the help of a technique called overloading member functions. This increases your classes’ adaptability and user-friendliness. Here is the syntax and an example of overloading a member function in C++:
Syntax:
// member function
void displayDetails(int mileage) {
cout << " " << mileage << endl;
}
// overloaded function with different types of parameters
void displayDetails(double mil) {
cout << " " << mil << endl;
}
Example:
#include <iostream>
using namespace std;
// define car
class Car {
public:
// Define the function with int parameters
void displayDetails(int mileage) {
cout << "Mileage in Integer: " << mileage << endl;
}
// Define the function with double parameters
void displayDetails(double mil) {
cout << "Mileage in Double: " << mil << endl;
}
// Define the function with string parameters
void displayDetails(string name) {
cout << "Name: " << name << endl;
}
};
int main() {
Car car; // create object of Car
car.displayDetails(11); // Calls displayDetails(int)
car.displayDetails(14.5); // Calls displayDetails(double)
car.displayDetails("BMW"); // Calls displayDetails(string)
return 0;
}
Output:
Mileage in Integer: 11
Mileage in Double: 14.5
Name: BMW
Explanation:
In this example, the Car class has three overloaded displayDetails() functions, each accepting different parameter types i.e., int, double, and string. This allows you to call the same function name with different arguments, and refer to as overloading of a member function in C++.
Best Practices for Using Member Functions
Member functions play a critical role in object-oriented programming as well as in defining the behaviour of classes in C++. The following are some recommended practices to remember:
Encapsulation: Encapsulation: To modify them, use private members, and make member functions available to the public. By doing this, the data is protected from unwanted access.
Const Correctness: When a function doesn’t change the state of the object, use const member functions.
Use Virtual Functions: Implement virtual functions in base classes for polymorphic behaviour. Always provide a virtual destructor in base classes.
Use Inline Functions for Small Functions: If a member function is small and frequently called, consider declaring it as inline to optimise performance.
Avoid Using Friend Functions: While friend functions can be useful, excessive use can break encapsulation. Use them judiciously.
Overloading: Use function overloading to provide different versions of a function with different parameter types.
Static Member Functions: For operations that don’t require a particular object instance, use static member functions.
Using the Scope Resolution Operator: To make member functions easier to read, define them outside of the class declaration by using the Scope Resolution Operator (::).
Conclusion
In C++ programming, member functions are essential features that support information hiding, enable modular programming, and the manipulation of class data. It is important to know the different types of member functions and their access modifiers, and how to overload them for effective C++ programming. Knowing common member functions – instance, static, constant, friend, virtual, inline – enables developers to write effective high-quality codes. Best practices can be followed and developers would have their code reusable, as well as safe.
FAQs
What are member functions in C++?
The member functions in C++ are embedded within a class structure and act on the data and function members defined for the class. It provides the capability to create objects from that class such that encapsulation can be achieved, which is an aspect of object-oriented programming (OOP).
Example:
#include <iostream>
using namespace std;
class Circle {
private:
double radius;
public:
// Constructor to initialise the radius
Circle(double r) : radius(r) {}
// Static member function
static double circumference(double radius) {
return 2 * 3.14 * radius;
}
};
int main() {
Circle c(10); // Create an object of Circle with a radius of 10
cout << "Circumference: " << Circle::circumference(5) << endl;
return 0;
}
What is a non-member function in C++?
Non-member functions are functions that are implemented outside the definition of any class, and so cannot reach any of the private and protected member functions of that class disassociated with functionality defining that class.
Such functions are considered outside the classes and may be defined regardless of class objects. Non-member functions are useful for performing non-member related tasks or class object operator overloading which do not require knowledge of the object's internal states.
3. What is the difference between function and member function?
A function is a generic expression of a section of computer code that executes some action and is not described only in either the main or any other method scope. A member function, on the other hand, is defined in the body of a class and has access to the data members that are secure and some that are semi-secure within that class.
What are static member functions in C++?
Static member functions are functions of a member of the class that do not act on a given instance of the class. These are invoked at the class level rather than at the object level. Static member functions are allowed to access only other static members of a class.
Syntax:
class ClassName {
public:
static void functionName() {
// function body
}
};
How do friend functions work in C++?
In C++, functions that are not part of a class yet have access to its protected and private members are known as friend functions. The friend keyword within the class definition is used to declare a friend function.
Example:
#include <iostream>
using namespace std;
class Rectangle {
private:
int length;
public:
Rectangle(int l) :length(l) {}
// Friend function declaration
friend int getLength(Rectangle& r);
};
// Friend function definition
int getLength(Rectangle& r) {
return r.length; // Access private member
}
int main() {
Rectangle r(10);
cout << "Length of Rectangle: " << getLength(r) << endl; // Calls the friend function
return 0;
}
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.