Now, let’s look at some of the special member functions that can be defined in C++ classes. The following are the various types of Member functions:
These are the basic member function, which doesn’t have any special keyword like static etc. as a prefix. Syntactically,
return_type functionName(parameter_list)
{
function body;
}
By declaring a function member as static, you make it independent of any specific class object. A static member function can be called even if there are no objects of the class, and static functions are accessed by using only the class name and the scope resolution operator::.
A static member function can only access static data members, other static member functions, and external functions.
Syntax:
class_name::function_name (parameter);
When the const keyword is used in the function’s declaration, the function becomes const. The purpose of const functions is to prevent them from modifying the object on which they are called. Syntactically,
// basic syntax of const Member Function
void fun123() const
{
// statement
}
By default, all member functions defined within the class definition are declared as Inline. We shall learn more about it in the next topic.
If a function is defined as a friend function, the function can access a class’s private and protected data. The use of the keyword friend informs the compiler that a given function is a friend function. To access the data, a friend function should be declared inside the class’s body, beginning with the keyword friend. For instance,
#include<iostream>
using namespace std;
class A
{
int x;
public:
A()
{
x=10;
}
friend class B; //friend class
};
class B
{
public:
void display(A &t)
{
cout<<endl<<"The value of x="<<t.x;
}
};
main()
{
A a;
B b;
b.display(a);
return 0;
}
The value of x=10
Note: we can also make an entire class as friend class.
Note: also read about Member Functions of Class in C++
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
You are given two singly linked lists that intersect at some node. Your task is…
A builder plans to construct N houses in a row, where each house can be…
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…