pointing a variable to a member function outside a class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wilintec
    New Member
    • Apr 2012
    • 1

    pointing a variable to a member function outside a class

    Hello, my question is this.
    In C++, how do i call a method member of class A from a class B, using a pointer.
    By the way Class A and B are of different types.

    I read that when a pointer is pointing to member function it can only point member functions within the class. But how can i point to a member function outside the class.?????



    for example

    class A
    {
    public:

    int add(int x) {

    return x+x;
    }
    };
    int main()

    {

    typedef int (A::*pointer)() ;
    pointer func = &A::add;
    A objt;
    B objt2;

    obt2.*func(2);// the compiler give me an error of incompatible with object type ‘B’


    return 0;
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    If you are in class A and need to call a method on class B then a class B object (or a pointer to it) must be a member variable of class A:

    Code:
    class A
    {
       public:
         void MethodA();
       private:
       B obj;
    };
    or
    Code:
    class A
    {
        public:
         void MethodA();
       private:
       B* ptr;
    };
    Then in your code for A::MethodA():

    Code:
    void A::MethodA()
    {
        obj.MethodB();
      //or if you have the address of a B object.
        ptr->MethodB();
    }
    Then your main():

    Code:
    int main()
    {
       A obj;  
       obj.MethodA();
    }
    Of course, other member functions of A (like the constructors) must take care of either creating the B object or getting the address of it.

    Comment

    Working...