Home » C++ programming language

Defining member function outside of the class in C++

A member function can be defined outside of the class too; here we will learn how to define a class member function inside and outside of the class?

Defining member function inside of the class definition (member function definition with declaration)

Consider the following syntax

class class_name
{
	private:
		declarations;
	public:
		function_declaration(parameters)
		{
			function_body;
		}
};

Here is the example

#include <iostream>
using namespace std;

class Example
{
	private:
		int val;
	public:
		//function to assign value
		void init_val(int v)
		{
			val=v;
		}
		//function to print value
		void print_val()
		{
			cout<<"val: "<<val<<endl;
		}
};

int main()
{
	//create object
	Example Ex;
	Ex.init_val(100);
	Ex.print_val();
	
	return 0;
}

Output

val: 100

In the above example, public member functions init_val() and print_val() are defined inside the class definition.


Defining member function outside of the class definition

A public member function can also be defined outside of the class with a special type of operator known as Scope Resolution Operator (SRO); SRO represents by :: (double colon)

Let’s consider the syntax

return_type class_name::function_name(parameters)
{
	function_body;
}

Here is the example

#include <iostream>
using namespace std;

class Example
{
	private:
		int val;
	public:
		//function declarations
		void init_val(int v);
		void print_val();
};
//function definitions
void Example::init_val(int v)
{
	val=v;
}

void Example::print_val()
{
	cout<<"val: "<<val<<endl;
}
int main()
{
	//create object
	Example Ex;
	Ex.init_val(100);
	Ex.print_val();
	
	return 0;
}

Output

val: 100





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.