Member Functions Defined Outside The Class in C++


Member Function Defined Outside the Class


Before this we have use member function inside the class.This need is not always be the case.Now we will discussed an example of distance class in which member function add_dist( ), that was not defined within the distance class definition.It is only declared inside the class with the statement .

void add_dist ( distance , distance ) ;


so by an example you can easily understand this topic





Defining member functions outside the class

#include <iostream>
using namespace std;
class Distance                              // Be careful using Distance D is capital .
{
private:
            int feet;
            float inches;
public:
            Distance (): feet(0),inches(0.0) // no argument constructor
            {}
            Distance (int f,float i):feet(f),inches(i)    //two argument constructor
            {}
            void get()
            {
                        cout<<"enter feet";
                        cin>>feet;
                        cout<<"enter inches";
                        cin>>inches;
            }
            void print()
            {
                        cout<<"feet is"<<feet;
                        cout<<"inches is "<<inches;
            }
            void add_dist(Distance,Distance);
};
void Distance ::add_dist(Distance d2,Distance d3)
{
            inches = d2.inches + d3.inches;
            feet=0;
            if(inches>=12)
            {
                        inches -=12;
                        feet++;
            }
            feet += d2.feet + d3.feet;
}
void main ()
{
            Distance d1,d3;
            Distance d2(12,6.43);
            d1.get();
            d3.add_dist(d1 , d2);   // d3=d1+d2
            d1.print();
            d2.print();
            d3.print();
}


In this example you see that member function defined outside the class . Here you can see that scope resolution operator is used that is :: .