c++11cppunit

C++ Access member function using pointer


I am not able to access member function using pointer.Find the below code and Error message The Error message is mentioned here error: request for member ‘getstream’ in ‘* objA.A::getfunction()’, which is of non-class type ‘int’ ret = objA.getfunction()->getstream();

#include <iostream>

using namespace std;

class A {
    public: 
    int *getfunction();
    int getstream();
};
int* A::getfunction()
{
      static  int a;
     a= getstream();

    return &a;
}

int getstream()
{
    return 1;
}
int main()
{
int *ret;
A objA;
ret = objA.getfunction()->getstream();
cout << ret;
return 0;
}

Solution

  • If you want to achieve a syntax like objA.getfunction()->getstream(); in your main function, you can do it with class A implementation similar to this :

    #include <iostream>
    
    using namespace std;
    
    // class A declaration
    
    class A {
    
    public:
        // Nested class A::AFunction declaration
        class AFunction {
        public:
            int getstream();
        };
    
    private:
        AFunction *p_AFunction;
    
    public:
        A();
        ~A();
        A::AFunction *getfunction();
    
    }; // class A
    
    // class A member function implementations
    
    A::A() : p_AFunction(new AFunction()) {
    }
    
    A::~A() {
        delete p_AFunction;
        p_AFunction = nullptr;
    }
    
    A::AFunction *A::getfunction() {
        return p_AFunction;
    }
    
    // Nested class A::AFunction member function implementations
    
    int A::AFunction::getstream() {
        return 1;
    }
    
    // main function
    
    int main() {
        A objA;
        int ret = objA.getfunction()->getstream();
        cout << ret;
        return 0;
    }
    

    If you want A::getfunction() function to return a function pointer to a member function in class A, and then invoke it in main function, you can have a implementation similar to this :

    #include <iostream>
    
    using namespace std;
    
    // class A declaration
    
    class A {
    
    public:
        typedef int (A::*AMemberFuncPtr) ();
    
    private:
        AMemberFuncPtr fn_getstream;
    
    public:
        A();
        A::AMemberFuncPtr getfunction();
    
    private:
        int getstream();
    
    }; // class A
    
    // class A member function implementations
    
    A::A() : fn_getstream(&A::getstream) {
    }
    
    A::AMemberFuncPtr A::getfunction() {
        return fn_getstream;
    }
    
    int A::getstream() {
        return 1;
    }
    
    // main function
    
    int main() {
        A objA;
        int ret = (objA.*objA.getfunction())();
        cout << ret;
        return 0;
    }
    

    Also see the answer to Function pointer to member function.