Member Function In C++ | Definition, Declaration, Types & More!
Table of content:
- What Is Member Function In C++?
- How To Define A Member Function In C++?
- Types Of Member Functions In C++
- Operator Overloading Of Member Function In C++
- Default, Copy, & Move Constructors & Assignment Operators In C++
- Difference Between Friend Function & Member Function In C++
- Conclusion
- Frequently Asked Questions
A function that is defined as a class member is known as a member function in C++ programming. But what is a function? A function is a collection of statements that compute specific data and produce output. So, instead of writing the same code over and over again with different inputs, we can simply call the function every time we need that specific code executed. Functions are used for containing operations in a single reusable block of code and run only when they are called.
Then, member functions, i.e., class member function, can access all of the class's data members and are defined inside the class in one of the visibility modes, namely public, private, or protected. In this article, we will discuss what member functions are in C++, how to define a function of class, the types of member functions, and much more.
What Is Member Function In C++?
As specified before, member functions are functions defined within a class. They can access the values of the data members and can also carry out operations on the data members. Their definition may be included in or excluded from the class body. A member function in C++ can access both public and private class members.
Syntax for Member Function in C++
// Member function declaration
returnType functionName (arguments)
{//function body
};
Here,
- The functionName refers to the name of the function, with the returnType specifying the data type of its return value.
- The arguments refer to the parameters the member function can take.
- The curly brackets {} contain the function body, i.e., the operations that are performed on the data members of the class.
Additional points to note about a member function in C++ is that it can access the private data of members, whereas a non-member function is unable to do so.
- Also, they can be called by another member function directly without using a dot operator.
- Member function makes the program modular by increasing code reusability and making it easier to understand, hence making the code maintainable.
- Member functions also provide the ability to restrict access to the data of members of the class. This can be done by making specific functions private, thus ensuring that only the class itself may access or modify sensitive data.
Member functions are essential in C++ as they encapsulate the behavior and functionality of objects. They enable objects to interact with their data and serve as a means for other components of the program to modify the data.
Let us understand how member functions are declared and defined in a C++ program with the help of an example:
Output:
Enter 2 values: 3 3
Sum is = 6
Explanation:
In the above example-
- The code includes the <iostream> library, which allows input and output operations.
- Then, we define a class called add, which has three private data members, a, b, and c, of interger type.
- We also define a member function called sum inside the add class. It prompts the user to enter two values, a and b, using the cout command and read the input using cin command.
- The public function then calculates the sum of these values and stores it in c.
- In the main() function, we first create an object p of the add class.
- Then, using the dot pointer and p, we call the add() function.
- The sum is then displayed on the console using cout.
Time & Space Complexity: O(1).
How To Define A Member Function In C++?
There are mainly two ways to define a member function in C++. They are-
- Inside the class definition
- Outside the class definition.
We will discuss both of these ways in greater detail in the sections ahead, along with the help of examples.
Defining Member Function In C++ Inside The Class Definition
A member function can be both declared and defined within a class itself. When a member function is defined within a class, it is referred to as an inline function. All of the constraints and limitations that apply to inline functions also apply to functions declared within a class.
Syntax:
class MyClass{
private:
//Data Members variablespublic:
//Member Function
returnType functionName(argument){
//Function Definition
}
};
Here,
- In the code given above, you can see how a member function is declared and defined inside a class in C++.
- There is a class ‘MyClass, which contains the data members, and the member function named ‘functionName’, which is nothing but a normal function.
To better understand the concept, consider the following example:
Output:
Enter Radius 4
The Area of the Circle is = 50.24
Explanation:
In the C++ program above,
- We first define the Circle class, which has a private data member called rad (of float type).
- Also in the class is the member function called getradius(), which prompts the user to enter the radius of the circle using cout, stores it in the rad data member, and reads the input using the cin command.
- We define another void member function called calc_area within the Circle class. It calculates the area of the circle using the formula a = 3.14*rad*rad and displays it on the console.
- In the main() function, we first create an object c of the Circle class.
- We then call the getradius() member function on the c object, which prompts the user for input and stores the radius in the rad data member.
- The calc_area member function then calculates the area of the circle and displays it on the console.
- The program returns 0 to indicate successful execution.
Time & Space Complexity: O(1).
Defining Member Function In C++ Outside The Class Definition
In this case, the declaration and definition of the member function are not made together. That is, while the functions are declared inside the class, their definition is given outside.
However, the definitions of member functions are very similar to those of normal functions. They should have a function header and body. Unlike a normal function, a member function includes a membership identity label in the header. The identity label is used to indicate that the function belongs to a particular class.
Syntax:
return_type class_name :: function-name (argument declaration){
//Function body
}
Here,
- The class_name is the membership label or the name of the class to which the member function belongs.
- The function_name and the double colon (::) are the name of the function and the scope resolution operator, which tells the compiler that the function belongs to the class_name.
- The arguments and the return_type refer to the parameters the function takes and the data type of its return value, respectively.
To better understand the concept, consider the following example:
Output:
Enter Radius 4
The Area of the Circle is = 50.24
Explanation:
- The Circle class is defined in the example above, with a private data member called rad.
- It also contains a member function called getradius(), which is defined outside the class using the scope resolution operator. It prompts the user to enter the radius of the circle using cout, stores it in the rad data member, and reads the input using cin.
- We also define another member function, calc_area(), outside the class, which calculates the area of the circle using the formula a = 3.14*rad*rad and displays it on the console.
- In the main() function, we first create an object c of the Circle class and use it along with the dot operator to call the getradius() member function.
- This prompts the user for input and stores the radius in the rad data member.
- We also call the calc_area() member function on the c object, which calculates the area of the circle and displays it on the console.
- The program returns 0 to indicate successful execution
Time & Space Complexity: O(1).
Defining A Private Member Function In C++
Classes can contain private member functions for internal functionality, as well as to limit access to certain operations or data members. This ensures data integrity and encapsulation within the class. Note that private member functions cannot be invoked using the dot operator, even by objects.
Let us understand through an example how to declare a private member function:
Output:
Current count: 1
Current count: 2
Current count: 1
Explanation:
- In this program, we define a Counter class with a private count data member. It contains two public member functions, increment() and decrement(), which increment and decrement the count, respectively.
- The class also contains the private member function called displayCount() for displaying the current count using the cout command.
- Since the member function displayCount() is marked private, only the members of the class can access it. As a result, it shows the current count.
- Then, in the main() function, we create an object counter belonging to the Counter class.
- We use this object to call the increment() and decrement() functions using the dot operator.
- However, if we try to call the displayCount() function, it will lead to a compilation problem, as mentioned in the comments in the code.
This illustrates how private member functions can limit direct access to specific activities or information, ensuring encapsulation and managing the visibility of internal features within the class.
Time & Space Complexity: O(1)
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
Types Of Member Functions In C++
In C++, there are several types of member functions that can be defined within a class. Here are the common types of member functions:
Simple Member Function In C++
The most popular type of member function in C++ is the regular member function/ simple function. They are declared in a class and can be accessed and invoked by class objects. Regular member functions work on the class's data members and provide the class's principal functionality or behavior.
Syntax:
class MyClass{
public:
//Data Members Variables
returnType functionName(arguments){
//Function Body
}
};
Here,
- The functionName refers to the name of the function, and returnType to the data type of its return value.
- Arguments refer to the parameters that the function takes as input, and its code body is contained in the curly brackets {}.
To better understand the concept, consider the following example:
Output:
Sum = 11
Product = 30
Explanation:
- In the example above, we define a MathOperations class, which has two member functions, add() and multiply ().
- These ordinary member functions carry out simple mathematical calculations, addition, and multiplication of two integer type variables, a and b, respectively.
- In the main() function, we create two objects of the MathOperations class, num1 and num2.
- We then call the add() and multiply() functions on these objects using the dot operator and assign values 6 and 5 to num1 and num2, respectively.
- The function results are printed to the console using the cout commands in the respective functions.
Time & Space Complexity: The complexity of these functions is constant (O(1)) because the operations performed (addition and multiplication) take a constant amount of time regardless of the input.
Static Member Function In C++
Declaring a function member as static makes it independent of any specific class object. A static member function in C++ can be called even if there are no objects of the class. Also, they can be accessed simply by using the class name and the scope resolution operator (::).
In short, they do not have access to the object's data members, but they can access static data members and other static member functions. Now, let's take a look at the syntax and an example for the same.
Syntax:
Class MyClass{
private:
//Data Members
public:
static returnType functionName(argument) {
//Function Body
}
};
Here,
- The static keyword indicates that the function of the name, functionName, is of the static kind.
- Private and public are the access modifiers that control the visibility of the data and function members.
- The arguments and returnType specify the parameters input the function takes and the data type of its return value.
- The code/ statements of the function are contained in the curly braces {}.
Let us take an example, showing how the Static Member functions work:
Output:
The Area of the circle = 78.5397
Explanation:
- We first define a class called Circle, which has a private static data member pi and a public static member function calculateArea().
- The calculateArea() member function takes a float parameter radius and calculates the area of the circle using the formula pi*radius*radius. The result is displayed on the console using cout.
- We then define the pi static data member outside the class and initialize it with the value of 3.14159.
- In the main() function, we create an object c of the Circle and use it to call the calculateArea() member function, passing the value 5 as the radius.
- The area of the circle is calculated and displayed on the console.
- The program returns 0 to indicate successful execution.
Friend Member Function In C++
The friend function is a function that is declared using the friend keyword. Any number of classes can have a function specified as a friend. The friend function, unlike the member function, has full access to the class's private members. This is because it is a friend of the respective class.
A member function of one class can be the friend of another class. They can either be declared in public or the private part of a class without affecting its meaning. However, since it is not in the scope of the class, it cannot be called by using the object of that class.
Syntax:
class Myclass {
private:
//Data Members
public:
friend returntype functionName(argument)
};
Here,
- The friend keyword indicates that the function being created is a friend of MyClass.
- The returntype, functionName, and arguments refer to the data type of return value, the function's name, and the parameters it takes as arguments, respectively.
Example:
Output:
Data: 42
Explanation:
- Here, in this example, we create a class called Display with a private member called data and an initializer constructor.
- In the initializer, we use the friend keyword to declare the displayData() member function as a friend inside the class. It takes a constant reference to an instance of the Display class as a parameter.
- Note that the friend function can access the private members of an object of type Display.
- Outside the class, we define the displayData() function, which prints the member data's value using the cout command.
- Then, inside the main() function, we create an instance of the Display class Obj1 with a value of 42.
- Next, we call the displayData() function Obj1 as the argument. This prints the private data member of Obj1 to the console.
Time & Space Complexity: Since the operations performed are constant-time operations that do not depend on the input size or loops, this code example has an O(1) time complexity.
Constant Member Functions In C++
Constant member functions are those that do not change the state of the object. They are declared at the end of the function declaration with the const keyword. A constant member function in C++ can only access other const member functions and const data members of the class when called on const objects. Additionally, the const keyword can also be used to declare parameters and variables as constant, ensuring that their values are not modified during execution.
Syntax:
class ClassName {
public:
returnType functionName(arguments) const {
// Function body
}
};
Here,
- The const keyword indicates that the member function is constant, i.e., it will not modify the object to which it is applied.
- The rest of the syntax is similar to a normal function, where functionName, arguments, and returnType refer to the name of the function, the parameters it takes, and the data type of its return value, respectively.
Let us better understand with an example given below:
Output:
Area of the rectangle = 200
Explanation:
- In the example, we define a Rectangle class with two private data members, length and width.
- The class also has a public member function, Dimensions(), which takes two int parameters, len and wid, and stores them in the length and width data members, respectively.
- We define another member function, calculateArea(), using the const keyword. The function calculates the area of the rectangle using the formula length * width and displays it on the console using the cout command.
- In the main() function, we create an object R of the Rectangle class. We then call the Dimensions() member function on the R object, passing the values 20 and 10 as the length and width, respectively.
- Next, we call the calculateArea() member function on the R object, which calculates the area of the rectangle and displays it on the console.
- The program returns 0 to indicate successful execution
Time & Space Complexity: Since the operations performed are constant-time operations that do not depend on the input size or loops, this code example has an O(1) time complexity.
Virtual Member Function In C++
When a function in the base class and its derived class have the same name and prototype, the function in the base class is declared virtual. This ability of the derived class member function to surpass the base class function is known as function overriding.
- Virtual functions should not be static. It must belong to some class. A virtual function can be added to another class as a friend.
- In member functions, Constructors cannot be declared virtual, but destructors can. A pointer object can be used to access them.
- The prototype of the base class version of the virtual function and the prototype of the derived class function must be identical.
- The base pointer can point to any type of derived object, but it cannot point to the base class object.
Syntax:
virtual return_type function_name(arguments){
//body of function
}
Here,
- The virtual keyword indicates that the function is virtual and can be overridden.
- The function_name, arguments, and return_type refer to the name of the function, the parameters it takes as input, and the data type of return value, respectively.
Here is an example of a virtual Member function in C++:
Output:
Draw a circle.
Draw a square.
Explanation:
- We have a base class Shape in the example above, with a virtual member function draw().
- We then create two derived classes, called Circle and Square, that inherit from the Shape class. Both the classes override the draw() function with their own implementations.
- In the main() function, we create objects of the Circle and Square types, called circle and square, respectively.
- We then create references shapeRef1 and shapeRef2 of the base class Shape type and assign them to the appropriate objects.
- When we invoke the draw() function via these references, the relevant override function is invoked based on the actual object type.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Inline Function In C++
In C++, an inline member function is a function that is defined within a class declaration and tagged with the inline keyword. When a member function is specified as a function inline, the compiler understands that the function body should be placed immediately at each call site rather than being called a regular function.
Syntax:
class MyClass {
public:
inline returnType functionName(arguments) {
// Function body
}
};
Here,
- The inline keyword is used before the returnType (data type of return value) in the function definition to declare a member function as inline.
- The functionName and arguments refer to the name of the function and the input parameters it takes.
Here is an example of the Inline member function:
Output:
Square = 36
Explanation:
- In the example, we first define the Math class, which has a public inline member function called square().
- The square() member function takes an integer parameter, num, and returns the square of the number.
- In the main() function, we create an object math of the Math class. We then call the square() member function on the math object, passing the value 6 as the number to be squared.
- The squared value is stored in the result variable and is printed to the console using the cout command.
- The program returns 0 to indicate successful execution.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant time execution and a fixed amount of memory use.
Operator Overloading Of Member Function In C++
The assignment operator (=) can be overloaded as a member function to determine the behavior of assignment between objects of a class. It lets one object be allocated the value of another. When the assignment operator is used between objects, the assignment operator member function is invoked.
Syntax:
class MyClass {
public:
returnType operator+(argument) {
// Function body
}
};
Here,
- The operator keyword is followed by the symbol for the overloaded operator, here, the addition operator (+).
- The operator you choose is determined by the desired behavior you want to redefine for your class.
Here is an example of an operator overloading member function:
Output:
Count: 4
Explanation:
- In this case, the Counter class represents a simple counter, and the increment operator (++) is overloaded as a member function.
- The Counter class has a private data member count as well as a constructor that sets it to zero.
- We overload the increment operator, by operator++ member function to increase the counter by one. It returns the modified object's reference.
- In the main() method, we create a Counter object c and increment it by one using the overloaded increment operator (++c).
- The current count is then displayed using the getCount() member function and the cout command.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Default, Copy, & Move Constructors & Assignment Operators In C++
In C++, the default, copy, and move constructors, as well as the assignment operators, describe how objects are created, copied, and assigned. These functions are critical for managing the lifecycle and behavior of objects in a number of conditions.
Default Constructor In C++
A default constructor is a specific type of member function of a class used to generate objects without requiring arguments. When no specified initialization values are provided, it is used to initialize an object. If a class lacks any user-defined constructors, the compiler constructs a default constructor. It sets member variables to their default values (for example, 0 for integers, nullptr for pointers, and so on).
Syntax:
class MyClass {
public:
MyClass() {
// Default constructor implementation
}
};
Here,
- MyClass is the name of both the class and the default constructor, which should be the same.
- The curly brackets {} contain the body of the constructor.
Here is an example of the default constructor operator in C++:
Output:
The default constructor is called.
Explanation:
- As in this example, we define a class called DefaultClass, with a default constructor called DefaultClass() that does not accept parameters.
- In the main() function, we create an object obj of the DefaultClass using the constructor.
- This leads to execution of the code within the default constructor, outputting 'Default constructor is called' using the cout command.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Copy Constructor In C++
A copy constructor is a special member function of a class whose purpose is to create a new object that is an exact replica of an existing one. The copy constructor makes a copy of an existing object of the same class to produce a new object. It is used to initialize an object with another object of the same class or when a function receives an object by value. It copies the data from the source object to the newly generated object member by member.
- You can define an implementation for the copy constructor, which will create a copy of the source object (other) within the newly created object by performing the necessary steps.
- It typically involves copying the values of member variables or allocating new resources and copying the contents of the source object to the new one.
Syntax:
class MyClass {
public:
MyClass(const MyClass& other) {
// Copy constructor implementation
}
};
Explanation:
- The name of the copy constructor is the same as the class name, i.e., MyClass().
- The term const refers to the parameter of type, and MyClass& refers to the reference to the constant object of the class.
Here is an example of the copy constructor operator in C++:
Output:
Constructor is called with value: 50
Copy constructor is called with value: 50
Explanation:
- In this example, we create a class called CopyClass with a constructor that uses an initializer list.
- We also have a copy constructor defined with a const CopyClass& parameter. Both the constructors print a phrase using the cout command.
- Then, in the main() function, we create an object Obj1 of the CopyClass type and initialize it with the value of 50, thus invoking the constructor.
- We then invoke the copy constructor by creating another object Obj2 and initialize it as a copy of Obj1 (i.e., CopyClass Obj2 = Obj1).
- The actual copying takes place within the body of the constructor itself, where the relevant variables from the existing object are transferred to its newly created counterpart.
- This is verified as the phrase contained in the copy constructor is printed to the console.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Move Constructor In C++
The move constructor creates a new object by efficiently transferring resources (for example, memory) from an existing object of the same class. It is used to initialize an object with a value (for example, a temporary object or the result of a function that returns by value).
- It is used to create a new instance efficiently by transferring resources such as pointers or dynamic memory from the source (other) to the new object.
- It transfers resource ownership from the source object to the newly formed object, leaving the source object valid but unidentified.
- It is commonly used to improve performance by reducing unnecessary copies of costly-to-move resources.
Syntax:
class MyClass {
public:
MyClass (MyClass&& other) {
// Move constructor implementation
}
};
Here,
- The name of the move constructor is the same as the class name, i.e., MyClass.
- This is followed by a parameter of type MyClass&&, i.e., rvalue reference.
- Implementations to transfer ownership of such resources should be defined inside the move constructor.
Here is an example of the move constructor in C++:
Output:
Constructor is called with value: 50
Move constructor is called with value: 50
Explanation:
- Integer pointer data (int* data) is defined as a member of the MoveClass class in the example above.
- We also define a constructor in the class called MoveClass(int val), which allocates memory for an integer dynamically using the new keyword and initializes it with the value passed as an argument.
- It also prints a message with the value of the data variable using the cout command.
- Next, we define a move constructor MoveClass(MoveClass &&other), which accepts a reference to another MoveClass object as a parameter.
- The value of the data pointer of the current object is assigned to the data pointer of the other object within the move constructor.
- The move constructor then prints a phrase indicating that the value of data being moved is set to nullptr so that there is no double deletion of memory.
- In the main() function, we create an object Obj1 of type MoveClass with an integer argument, 50. This invokes the constructor and prints the message to this effect.
- Next, we create another object, Obj2, and move(Obj1), which invokes the move constructor. Using Obj1 as a reference, this move constructor is called.
- During the move constructor, the data pointers to objects Obj1 and Obj2 are set to nullptr.
- The result is the printing of a message indicating the value of the data that is being moved.
Copy Assignment Operator In C++
By using the copy assignment operator, the value of an object is copied to another object of the same class. It is invoked when an object is assigned the value of another object using the assignment operator (=). It replaces the existing data in the target object with data copied from the source object. Checks and modifications can be conducted for your class's requirements before copying them over. It returns a reference to the target object in order to facilitate chaining assignments.
Syntax:
class MyClass {
public:
MyClass& operator=(const MyClass& other) {
// Copy assignment operator implementation
return *this;}
};
Here,
- MyClass& operator=(const MyClass& other) is the signature of the copy assignment operator function.
- The 'MyClass& other' refers to the constant parameter that the assignment operator function takes.
- Inside the function, you can define an implementation that outfits the copied member variables of 'other' into 'this.'
- The term return *this, indicates the assignment chaining.
Here is an example of the copy assignment operator in C++:
Output:
Constructor1 is called with value: 50
Constructor2 is called with value: 40
Copy assignment operator is called with value: 50
Explanation:
In the example above, we
- First, define a class called CopyAssign, with one public data member called value, of integer type.
- We then define a constructor with an initializer list, i.e., CopyAssign(int val) : value(val), which initializes the variable and prints a phrase using the cout command.
- There is also a copy assignment operator function, which is invoked when the assignment operator (=) is used between two objects of the same class.
- It performs a self-assignment check using the condition this != &other. This ensures that the assignment is not performed when an object is assigned to itself.
- Assuming the objects are distinct, the other object's value is copied to the current object (*this), and a phrase to that effect is printed to the output console using the cout command. In this case, the value member is assigned from other.value.
- Then, in the main() function, we first create an object Obj1 and then an object Obj2. This invokes the constructor with values 50 and 40.
- Next, Obj2 is assigned the value of obj1 using the assignment operator. This invokes the copy assignment operator function, and a phrase to that effect it printed on the console.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Move Assignment Operator In C++
The move assignment operator's aim is to transfer resource ownership from the source object to the target object. Move assignment operators (=) in C++ provide efficient resource transfers from one object to another by transferring resources quickly.
Syntax:
class MyClass {
public:
MyClass& operator (MyClass&& other) {
// Move assignment operator implementation
return *this;}
};
Here,
- The operator keyword indicates that we are declaring an assignment operator function.
- 'MyClass&& other' is the single argument taken by the function. Here, the right-hand side, i.e., MyClass&& representing an rvalue reference to MyClass).
- The curly braces{} contain the implementation which carries out the necessary steps when moving from one object of the same class to another.
Here is an example of the move assignment operator in C++:
Output:
Constructor is called with value: 30
Constructor is called with value: 40
Move assignment operator is called with value: 30
Explanation:
- In the example, we define a MyClass class with a public integer data pointer member pointing to variable data. The class also has two constructors, one default and one user-defined.
- The first constructor assigns the pointer to the value nullptr, and the second uses the new keyword to allocate memory to int val. Both print a phrase to the effect that they were called, using the cout command.
- We also have a move assignment operator function, which is implemented when the equal sign (=) is situated in an rvalue expression (e.g., move()).
- It also contains a self-assignment check, which is identified by the condition (this != &other) which stops an object from being moved to itself.
- The move assignment operator is used when transferring ownership of a dynamically allocated resource from one object to another.
- Then, in the main() function, we create two objects, Obj1 and Obj2.
- This invokes the constructor with the values 30 and 40 for Obj1 and Obj2, respectively.
- Then, we move Obj1 to Obj2 using the syntax obj2 = move(obj1).
- This invokes the move assignment operator. It works by deleting the current object's resource, copying the pointer from other.data, and nullifying data in other.
Time & Space Complexity: The time and space complexity of the above program is O(1), suggesting constant-time execution and a fixed amount of memory use.
Difference Between Friend Function & Member Function In C++
Feature | Member Function | Friend Function |
---|---|---|
Declaration | Defined inside the class definition. | Declared inside the class but defined outside. |
Access to Members | Has direct access to all members (public, protected, private) of the class. | Has access to the class's private and protected members but not directly to public members. |
Invocation | Called using an object of the class. | Called using an object of the class or without any object (as it's not bound to any object). |
Relationship | Implicitly associated with a class as a member. | Not a member of the class; it's a separate function with a special declaration. |
Scope | Implicitly has the 'this' pointer to the object. | Doesn't have access to the 'this' pointer. |
Visibility | Inherits access permissions based on member access specifiers. | Doesn't inherit access permissions; explicitly granted friendship. |
Function Purpose | Primarily used for operations related to the object's data. | Used for operations that need to access private/protected members of the class. |
Access Control | Restricted by member access specifiers (public, protected, private). | Can access private and protected members when granted friendship. |
Function Overloading | It can be overloaded within the class. | It can be overloaded within the class and in global scope. |
Inheritance | Inherited by derived classes. | Not inherited by derived classes. |
Conclusion
A member function in C++ is a cornerstone of object-oriented programming, providing a structured and efficient way to define behavior and manipulate class objects. They contribute to code organization, data encapsulation, and the realization of key principles such as inheritance and polymorphism. By understanding and effectively using member functions, you can create well-designed and maintainable C++ programs that leverage the full power of object-oriented concepts.
Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)
Frequently Asked Questions
Q. Are method and member functions the same?
Methods and member functions are often used interchangeably in object-oriented programming. Both refer to functions defined within a class that operates on the class's data members. The term method is more commonly used in object-oriented programming languages such as Java and Python, while the term member function is frequently used in C++.
Q. What is the difference between const and static in CPP?
Feature | const | static |
---|---|---|
Purpose | Defines a constant value for a variable. | Modifies the scope and lifetime of a variable or function. |
Applies to | Variables and function parameters. | Variables, functions, and class members. |
Value Mutability | Value cannot be changed after initialization. | Value can be modified. |
Memory Location | It can be stored in read-only memory. | Stored in the data segment or heap memory. |
Scope | Limited to the scope where it is defined. | It may have a file, function, or class scope. |
Lifetime | Lifetime of the variable it's associated with. | Depends on where it's used (varies). |
Initialization | It must be initialized when declared. | If used for variables, it must be initialized at the point of definition or initialized explicitly if outside class. Functions are defined only once. |
Class Members | It can be used to define read-only class members. | It can be used to define class-level members shared among all instances. |
Storage | Each instance of a class has its own copy. | Shared among all instances of a class. |
Linkage | No linkage (usually internal linkage). | It can have internal or external linkage. |
Example | const int max_value = 100; |
static int instance_count; |
Q. What are the 5 special member functions in C++?
In C++, the five special member functions are also known as the special methods. These functions are automatically generated by the compiler under certain conditions if they are not explicitly defined in your class. They are essential for proper object management and behavior in various situations. The five special member functions are:
-
Default Constructor: This constructor is called when an object is created without any arguments. It initializes the object's members to their default values. If no constructors are defined in a class, the compiler provides a default constructor.
-
Destructor: The destructor is called when an object is about to be destroyed, typically when it goes out of scope or is explicitly deleted. It is responsible for releasing any resources held by the object, such as dynamic memory allocations. If no destructor is defined, the compiler provides an implicit one.
-
Copy Constructor: The copy constructor is called when a new object is being created as a copy of an existing object. It defines how the copy should be made. If not defined by the user, the compiler generates a default copy constructor.
-
Copy Assignment Operator: This function is called when an existing object's value is assigned to another existing object of the same type. It defines how the assignment should take place. If not defined by the user, the compiler generates a default copy assignment operator.
-
Move Constructor: Introduced in C++11, the move constructor is used when an object's resources are transferred from one object to another, typically during moves or certain optimizations. It is more efficient than copying large objects. If not defined by the user, the compiler generates a default move constructor.
Q. Which operator is used to access class members with class objects?
You can use the (dot) operator to access class, structure, or union members. Data members cannot be accessed directly; instead, the dot operator or arrow is used, relying on the object of class or pointer, respectively.
Here is a small example:
Output:
Inside Method
Inside Method
To access class members and data members, this example uses the dot operator (.) and arrow operator/ 'this' pointer (->).
When accessing members through objects, the dot operator is used, while when accessing members through pointers to objects, the arrow operator is used. Interacting with classes, structures, and unions is convenient and intuitive when using these operators.
Q. How many member functions are there in C++?
In C++, there are 5 types of member functions. These member functions include:
- Simple Member Function in C++: In a class, simple member functions are regular member functions. They can be accessed by both data members and member functions of the class. Functions like these can modify the state of a specific instance of a class. They are defined in the class declaration and can access both data members and other member functions.
- Static Member Function in C++: The static keyword is used to declare them, and they can be accessed using the class name followed by a scope resolution operator (::). The 'this' pointer is not accessible to static members, as they do not interact with particular objects. They can only access static data members and static member functions.
- Const Member Function in C++: The const keyword is used to declare const member functions that can only be called on const objects or objects accessed through const references. Their purpose is to ensure that a member function does not change the object's state. Const member functions treat non-mutable data members as const, so attempting to modify non-mutable data members or calling non-const member functions will cause a compilation error.
- Inline Member Function in C++: The inline keyword is used to define inline member functions within the class declaration. The compiler implicitly treats them as inline functions, which means their code is inserted directly at the call site instead of making a function call. By reducing overhead, inline functions can improve performance. They are typically used for small functions that are frequently called.
- Friend Function in C++: A friend function can be declared by using the friend keyword and the function prototype inside the class declaration. Friend functions have access to the private and protected members of a class without being a member of it. A friend function is useful when a function is not a member of a class but needs to operate on its private or protected members.
With these different types of member functions in C++, classes can be designed and interacted with in a more flexible and controlled fashion.
Q. How to access a private member function in C++ of a class using the object of the class?
All members of the class that are declared private may only be accessed by the member functions inside the class. Only the member or friend functions can access the class's private data of members. Any object or function outside the class cannot access them directly.
As an example, consider a banking application whose customer's account is represented by a BankAcc class. The class has a private member function called calcInterest(), which calculates interest on the account balance. Normally, this function should only be accessible internally within the class.
Output:
Current balance: 3000
Interest calculated: 150
Explanation:
- This example illustrates how the BankAcc class calculates interest on the account balance using the private member function calcInterest().
- In the class, this function is normally only called internally. However, in the Interest() public member function, we can directly access the private member function calcInterest().
- This allows us to apply interest directly to the account balance.
Q. What is the difference between a class object and a class member?
Class Object: Objects of a class are instances or objects. Class definitions serve as blueprints or templates for creating multiple instances of a class. Each class instance is called an object or a class object. Data (member variables) and behaviors (member functions) defined by the class are stored in objects.
In this example, we have a class called Shape. We can create multiple instances of that class representing different shapes. Each instance, such as shape1, shape2, and so forth, represents an object of the class.
class Shape {
// Class definition
};int main() {
Shape shape1; // shape1 is a class object
Shape shape2; // shape2 is a class object
// Perform operations on shape1 and shape2
return 0;
}
Class Member: Class members refer to a variable or function belonging to a class. It can be classified into two main categories:
- Member Variables: Member variables are variables declared inside a class, which hold data specific to each instance of the class. Objects in a class have their own copy of these variables. These variables define the objects' properties.
class Shape {
int length; // Member variable
public:
// Member functions
};
In the above example, “length” is a member variable of the Shape class.
- Member Functions: These are functions declared within a class that define the behavior or actions executed by the class's objects. Member functions have access to and can manipulate the class's member variables.
class Shape {
int length; // Member variable
public:
void area() {
// Perform acceleration operation
}
};
Area() is a member function of the Shape class in the preceding example. The structure and behavior of objects created from the class are collectively defined by member variables and the member function in C++ example above.
You might also be interested in reading the following:
- For Loop In C++| A Detailed Discussion (With Examples)
- Array Of Objects In C++ | A Complete Guide To Creation (Using Examples)
- C++ Exception Handling | Use Try, Catch, & Throw (+Examples)
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- Function Overriding In C++ | Examples, Working Mechanism & More!
Comments
Login to continue reading
And access exclusive content, personalized recommendations, and career-boosting opportunities.
asad 1 year ago
asad 1 year ago