Defining Member Function In C++





Class methods definitions  (Defining the member functions)

Member functions can be defined in two places:-

  • Outside the class definition

The member functions of a class can be defied outside the class definitions. It is only declared inside the class but defined outside the class. The general form of member function definition outside the class definition is:

 Return_type Class_name:: function_name (argument list)
{
Function body
}

Where symbol :: is a supe resolution operator.

[Note: Only the supe resolution operator identified the function as a member of a particular class.]

A program to add two numbers defining a member getdata () and display () inside a class named sum and displaying the result.

#include<iostream.h>
#include<conio.h>
Class sum
{
Int A, B, Total;
Public:
Void getdata ();
Void display ();
};
Void sum:: getdata ()
{
Cout<<” \n enter the value of A and B”;
Cin>>A>>B;
}
Void sum:: display ()
{
Total =A+B;
Cout<<”\n the sum of A and B=”<<Total;
}
Void main ()
{
Sum a;
a.getdata ();
a.display ();
getch ();
}

 

  • Inside the class definition

The member function of a class can be declared and defined inside the class definition.

Example

#include<iostream.h>
#include<conio.h>
Class sum
{
Private:
Int A, B, Total;
Public:
Void getdata ()
{
Cout<,”\n enter the value of A and B”;
Cin>>A>>B;
}
Void display ()
{
Total = A+B;
Cout<<”\n the sum of A and B=”<<total;
}
};
Void main ()
{
Sum a;
a.getdata ();
a.display ();
getch ();
}



Related posts:

  1. Class In C++ Class in c++ Class is a group of similar object....
  2. C++ Functions C++ Functions A function is meant for performing a specified...
  3. Composite Function. A single function formed by the combination of two or...
  4. Inverse Function. If a function is defined from set A to set...
  5. Exponential Function. Exponential function is the function in which the output is...