Back to C++
2026-04-278 min read

C++ Class Member Functions

Learn C++ Class Member Functions step by step with clear examples and exercises.

Why This Matters

Understanding C++ class member functions is essential for mastering object-oriented programming in C++. They allow you to encapsulate data and behavior within a class, making your code more modular, maintainable, and scalable. Familiarity with class member functions is crucial for writing efficient and effective C++ code, as well as for understanding complex systems and debugging issues that may arise during development.

Prerequisites

To fully grasp the concepts covered in this tutorial, it's important to have a solid foundation in the following topics:

  1. Basic C++ syntax and data types
  2. Classes and objects in C++
  3. Access specifiers (public, private, protected)
  4. Scope resolution operator (::)
  5. Function overloading
  6. Function prototypes
  7. Passing arguments by value and reference
  8. Pointers and references in C++
  9. Inheritance and polymorphism in C++
  10. Templates in C++ (optional but recommended for advanced topics)

Core Concept

Class member functions are functions that are defined within a class and operate on the data members of that class. These functions help to encapsulate data and provide an interface for users to interact with the class objects. There are three types of member functions:

  1. Member function (non-static): These functions can access both static and non-static data members of a class. They are called using the dot operator (.) or arrow operator (->). Non-static member functions have an implicit this pointer, which refers to the current object instance.
class MyClass {
int myNum;

public:
void setMyNum(int num) {
myNum = num;
}

int getMyNum() {
return myNum;
}
};
  1. Static member function: These functions can only access static data members of a class and do not have an implicit this pointer. They are called using the scope resolution operator (::). Static member functions are shared among all instances of the class, and they cannot access non-static data members directly; instead, they must be accessed using an object of the class or through the scope resolution operator.
class MyClass {
static int myNum; // Static data member

public:
static void setMyNum(int num) {
myNum = num;
}

static int getMyNum() {
return myNum;
}
};
  1. Constructor: A special type of function that is called when an object is created. Constructors do not have a return type and are used to initialize the data members of a class. There can be multiple constructors in a class with different parameter lists, known as constructor overloading. Constructors also have an implicit this pointer, which refers to the current object being constructed.
class MyClass {
int myNum;

public:
MyClass(int num) : myNum(num) {} // Constructor taking an integer argument
};

Worked Example

Let's create a simple Employee class that has member functions for setting and getting employee information, as well as a static member function to calculate the total number of employees.

#include <iostream>
using namespace std;

class Employee {
private:
string name;
int id;
static int totalEmployees;

public:
// Constructor
Employee(string n, int i) : name(n), id(i) {
totalEmployees++;
}

// Member function to get the employee's name
string getName() {
return name;
}

// Member function to get the employee's ID
int getID() {
return id;
}

// Static member function to calculate the total number of employees
static int getTotalEmployees() {
return totalEmployees;
}

// Static member function to set the total number of employees (for testing purposes)
friend void setTotalEmployees(int newTotal);
};

// Static member function to set the total number of employees (for testing purposes)
void setTotalEmployees(int newTotal) {
Employee::totalEmployees = newTotal;
}

int Employee::totalEmployees = 0; // Initialize static data member

int main() {
// Create three employee objects and print their names and IDs
Employee emp1("John Doe", 1);
Employee emp2("Jane Smith", 2);
Employee emp3("Alice Johnson", 3);

cout << "Employee 1: Name - " << emp1.getName() << ", ID - " << emp1.getID() << endl;
cout << "Employee 2: Name - " << emp2.getName() << ", ID - " << emp2.getID() << endl;
cout << "Employee 3: Name - " << emp3.getName() << ", ID - " << emp3.getID() << endl;

// Print the total number of employees
cout << "Total Number of Employees: " << Employee::getTotalEmployees() << endl;

// Set the total number of employees for testing purposes
setTotalEmployees(10);
cout << "New Total Number of Employees: " << Employee::getTotalEmployees() << endl;

return 0;
}

Common Mistakes

  1. Forgetting to initialize data members: If you don't explicitly initialize data members, they will be set to their default values (zero for integers and null for pointers). This can lead to unexpected behavior in your program. To avoid this, always initialize data members either in the constructor or through initializer lists.
  1. Misusing access specifiers: Incorrect use of public, private, or protected access specifiers can expose data members unintentionally or make them inaccessible when needed. Make sure to carefully consider the appropriate level of access for each data member and function.
  1. Not understanding the difference between static and non-static member functions: Static member functions cannot access non-static data members directly; they must be accessed using an object of the class or through the scope resolution operator. Non-static member functions can access both static and non-static data members directly.
  1. Ignoring the order of initialization: In a class with multiple constructors, the constructor with no arguments is called the default constructor. It gets called when you create an object without providing any arguments. The order of initialization matters: base classes are initialized before derived classes, and static members are initialized before non-static members.
  1. Not properly managing memory: When using dynamic memory allocation (new and delete), make sure to always deallocate memory that has been allocated to avoid memory leaks.

Practice Questions

  1. Write a class Circle that inherits from the Shape class (assuming it exists) and overrides the getArea() function to calculate the area of a circle more efficiently using the formula πr².
  1. Add a static member function called getNumberOfObjects() to the Shape class, which returns the total number of Shape objects that have been created so far.
  1. Create a derived class Square from the Shape class and override the getArea() function to calculate the area of a square more efficiently using the formula 4a².

FAQ

  1. What is the purpose of the this pointer in C++? The this pointer is an implicit pointer that represents the current object. It can be used to access non-static member functions and data members of a class.
  1. Can I call a static member function using the dot operator (.) or arrow operator (->)? No, you cannot use either the dot operator or arrow operator to call a static member function. Instead, you should use the scope resolution operator (::).
  1. Why can't I access non-static data members from a static member function? Static member functions do not have an implicit this pointer, so they cannot directly access non-static data members of a class. To work around this, you can pass the object as an argument to the static member function or use friend functions.
  1. What happens when I create multiple objects of the same class with different constructors? When you create multiple objects of the same class with different constructors, each object gets its own copy of the data members. The constructor that matches the provided arguments is called for each object. If a constructor does not provide an initial value for a data member, it will be set to its default value.
  1. What is the difference between a static class member and a global variable? A static class member is a variable or function that belongs to a class but is shared among all instances of the class. Global variables, on the other hand, are variables that are visible throughout an entire program and can be accessed by any part of the code. Static class members have a limited scope within their class, while global variables have a global scope.
  1. What is constructor overloading? Constructor overloading allows you to define multiple constructors for a single class with different parameter lists. This enables you to create objects with different initial values for the data members based on the provided arguments. Each constructor has its own unique set of parameters, and the appropriate constructor is called based on the number and types of arguments provided when creating an object.
  1. What is a default constructor? A default constructor is a constructor that can be automatically generated by the compiler if no user-defined constructors are present in a class. It has no parameters and initializes all data members to their default values. If you provide any user-defined constructors, the default constructor will not be generated by the compiler.
  1. What is a copy constructor? A copy constructor is a special type of constructor that is used to create a new object as a copy of an existing object. It takes a reference to the existing object as a parameter and initializes the new object with the same values as the original object. The default copy constructor created by the compiler performs a shallow copy, which means that it only copies the pointers to the data members without creating separate copies of the actual objects pointed to by those pointers. To perform a deep copy (copying the actual objects), you can define a custom copy constructor or use the copy-and-swap idiom.
  1. What is the scope resolution operator (::)? The scope resolution operator (::) is used to access global variables, static class members, and namespace-qualified names. It allows you to explicitly specify the scope of a name when there are multiple entities with the same name in different scopes. For example, using :: before a member function name indicates that you want to call the static member function rather than an instance member function.
  1. What is a friend function? A friend function is a non-member function that has access to the private and protected data members of a class. It is declared as a friend within the class definition using the friend keyword. Friend functions can be useful when you need to perform operations on the data members of a class without defining a member function for each operation. They are not bound to any specific object instance, unlike member functions.
C++ Class Member Functions | C++ | XQA Learn