Member-function-definition in C++ .

In this session i have discussed member function definition in C++ .


There are two ways to define the member function of class .

1-Outside the class definition

2-Inside the class definition


Outside the class definition

The member function declared inside the class but define seperatly out side the class .

Class Syntax :

    return-type class-name :: function-name(argument)
    {
        function-body
    }
    

Example : Write a program that demonstrate the outside the class definition .

    #include<iostream>
    using namespace std;  
    class ABC
    {
       
       public :
       void show();
    };
    void ABC :: show()
    {
            cout<<"\nWelcome to androidatpoint ";
    }
    int main()
    {
        ABC obj;  //object created
        obj.show(); //show function called
        return 0;
    }
OUTPUT : Welcome to androidatpoint

Inside class definition

The member function that is declare and define inside the class .

Example : Write a program that demonstrate the inside the class definition .

    #include<iostream>
    using namespace std;  
    class Operation
    {
        int x=20, y=10, result = 0;
        public :
        void sum()
        {
            result=x+y;
            cout<<"\nSum : "<<result;
        }
        void sub()
        {
            result = x - y;
            cout<<"\nSub : "<<result);
        }

    };
    int main()
    {
        Operation obj;
        obj.sum();
        obj.sub();
    }
OUTPUT : Sum : 30
         Sub : 10 

Example : Write a program in which use a function to reverse the given number using class .

    #include<iostream>
    using namespace std;  
    class Operation
    {
        int rem=0, rev=0;
        public :
        void reverse(int n)
        { 
            while(n>0)
            {
                rem = n % 10;
                rev = (rev * 10 )+ rem;
                n = n / 10;
            }
            cout<<"Reverse Number is "<<rev;
        }
    };
    int main()
    {
        Operation obj;
        obj.reverse();
    }
    
OUTPUT : Reverse Number is : 123

Example : Write a program in which use a method to sum the individual digit of the given number using class .

    #include<iostream>
    using namespace std;  
    class Operation
    {
        int rem=0, s=0;
        public :
        void Sum(int n)
        { 
            while(n>0)
            {
                rem = n % 10;
                s = s+ rem;
                n = n / 10;
            }
            cout<<"Sum Number is "<<s;
        }
    }
    int main()
    {
        Operation obj;
        obj.sum(123);
    }
    
OUTPUT : Sum : 6
          

Welcome to AndroidATPoint.

back image                     next image