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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…