coderz.py

Keep Coding Keep Cheering!

Types of Class Member Functions in C++

Accessing Elements

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:

  • Simple functions
  • Static functions
  • Const functions
  • Inline functions
  • Friend functions
Simple 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;
}
Static Member functions:

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); 
Const Member function:

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
}
Inline functions:

By default, all member functions defined within the class definition are declared as Inline. We shall learn more about it in the next topic.

Friend functions:

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;
}
Output:
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++

Follow Me

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement