Pointer-to-function-in c++ .

In this session i have discussed pointer to function in C++ .


We will know the pointer to function lets see the below code this is the way by which you can declare the pointer to function .

    int(*add)();//pointer to function
    

Here * operator is with add which is a function name. And it did the same that we wanted to do. .


Example : Write a program that demonstrate the pointer to function .

    #include<iostream>
    using namespace std;   
    int add();
    int main ()
    {
        int sum;
        int (*ptr)();
        ptr = &add;
        sum = (*ptr)();
        cout<<"The sum is "<<sum;
    }
    int add()
    {
        int a, b;
        cout<<"Enter first number";
        cin>>a;
        cout<<"Enter second number";
        cin>>b;
        return a+b;
    }

    
    OUTPUT : Enter the first number 10
             Enter the second number 20
             sum is 30
    


Example : Write a program that demonstrate the pointer to function with argument .

    #include<iostream>
    using namespace std;   
    int add (int a,int b);
    int main ()
    {
        int sum;
        int a,b;
        a=20;
        b=10;
        int (*ptr)(int ,int);
        ptr = &add;
        sum = (*ptr)(a,b);
        cout<<"The sum is "<<sum;
    }
    int add(int a,int b)
    {
        return a+b;
    }
    OUTPUT : The sum is 30
    

Welcome to AndroidATPoint.

back image                     next image