Defining member functions inside or outside the class in C++
The member functions of a class can be defined in two ways:-
- Inside the class
- Outside the class
Defining member functions inside the class in C++
This is the most common way of defining members functions of a class.
In this case we define member functions of a class in the same manner as we define normal functions.
Functions defined inside a class are automatically inline. Normally data members of a class are defined as private and member functions of a class are defined as public members of a class.
Example:
using namespace std; class student { public: //Member function inside the class void display() { cout<<”Inside the class”; } };
int main()() { student obj; obj.display(); return 0; } Defining member functions outside the class in C++
We can also define member functions outside a class. There are two steps involved in defining member function outside the class.
- Declaration of member function
- Member Function definition
Declaration of member function
We need to declare the member functions inside the class but the function body is created outside the class.
Syntax to declare a member function as:
class <class_name> { visibility mode: member function(); }
Example:
class student { public: void display(); //Member function Declaration };
Member Function definition
After declaring member function inside the class, we need to define its body outside the class.
Syntax:
Return-type class_name::function name(Agument_list) { function-body }
- Return-type refers to the return type of member function.
- Class_name is the name of class in which member function is declared.
- Argument_list is the list of various formal arguments passed to the function.
- Function-body contains the valid statements of C++ which will be executed as a part of the function.
Example:
using namespace std; class student { public: //Member function declaration inside the class void display(); }; //Member function definition outside the class void student::display() { cout<<”Outside the class”; }
int main()() { student obj; obj.display(); return 0; }