Member Function’s Definition Outside Class
Submitted by Muzammil Muneer on Wednesday, October 22, 2014 - 10:19.
Member function’s definition outside Class
In this part you will learn: 1. Why we need to define function outside class 2. Syntax 3. Scope resolution operator 4. Program Defining Member function outside Class Till now, we have written many programs using class in the previous topic. In those classes, we had member functions too. Those member functions were defined right there because of their small size. But think about a huge project, with hundreds of member functions of a single class. Moreover the member functions we have defined are small ones, in real programming the size of a member function can be much greater. Won’t it make our program difficult to read and understand? Even finding a function definition would become difficult. C++ provide us with an option of defining member functions separately. That means, the programmer have to just declare the function in the class and he/she can define it anywhere in the code. By doing so, the readability of the code increases. Syntax Following is the syntax of defining a member function outside the class. class Class_Name { return_type Function_name(parameters); } return_type Class_Name_to_which_Function_belongs :: Function_name(parameters) { //function definition } In the above syntax we have used scope resolution operator ( :: ) Scope resolution operator (::) is a special type of operator used to access members of a class. Since we want to access member function of a class we will use scope resolution operator. Program with member Function definition outside Class In this example I have defined the member function of a Class. Basic Step:- #include<iostream>
- #include<conio.h>
- using namespace std;
- class fraction
- {
- private: //access specifier
- int num;
- int denom;
- public:
- void getfraction(){
- cout << "Fraction is: " << num << "/" << denom;
- }
- void setfraction(){
- cout << "Enter numerator: ";
- cin >> num;
- cout << "Enter denominator: ";
- cin >> denom;
- }
- fraction addfraction(fraction f);
- };
- fraction fraction :: addfraction(fraction f){
- fraction sum;
- sum.num = (this->num*f.denom) + (this->denom*f.num);
- sum.denom = this->denom*f.denom;
- return sum;
- }
Add new comment
- 68 views