Thread: call methods across classes

  1. #1
    Registered User
    Join Date
    Jun 2007
    Posts
    99

    call methods across classes

    Code:
    class A
    {
         void foo()
         {
    
         }
    };
    
    class B
    {
         void bar()
         {
    
         }
    };
    Is there a possibility I can call foo() from bar() without creating objects.

    Restrictions: * Cannot use static methods
    * Cannot create class Hierarchies
    * Cannot use Friend Functions

  2. #2
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Quote Originally Posted by vb.bajpai View Post
    Is there a possibility I can call foo() from bar() without creating objects.
    No, not with those restrictions. Either you need to create an object or the functions must be static.

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  3. #3
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Since foo() is private, nobody can call it except class A.

  4. #4
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    Code:
    class A
    {
    public:
         void foo()
         {
    
         }
    };
    
    class B
    {
    public:
         void bar( A &a_inst )
         {
            a_inst.foo();
         }
    };
    
    /* ... */
    
    int main( void ) {
      A a;
      B b;
    
      b.bar( a );
    
      return 0;
    }
    But foo has to be a public function unless you want to declare B as a friend class within A:

    Code:
    class A {
    friend class B;
    
    private:
      void foo() {
        std::cout<< "A::foo() method called\n";
      }
    
    public:
    
    };
    
    class B
    {
    private:
    
    
    public:
      void bar( A &a_inst ) {
        a_inst.foo();
      }
    };
    
    /* ... */
    
    int main( void ) {
      A a;
      B b;
    
      b.bar( a );
    
      return 0;
    }
    Last edited by twomers; 09-11-2007 at 08:29 AM.

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by cpjust View Post
    Since foo() is private, nobody can call it except class A.
    I think the failure to make it public was just an oversight on the OP's part.

    The other folks are right. In order to call a non-static member function, you must have an instance of the class. A non-static member ALWAYS is associated with an object. If you have no object, you have no member function.

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by QuantumPete View Post
    No, not with those restrictions. Either you need to create an object or the functions must be static.
    That's not precisely true. It is technically possible by subverting the C++ type system. For example;
    Code:
       A *x = (A *)0;
       x->foo();                // assumes A::foo() is accessible at this point
    The problem with this is that x is treated as a pointer to a valid A, but it really isn't. Dereferencing x (which is a prerequisite for calling A::foo() in the call x->foo()) yields undefined behaviour. The results of undefined behaviour (as that term is defined in the C++ standard) are unconstrained. There is therefore no guarantee that A::foo() is actually called (the program might crash with a core dump before it is called), no guarantee that it will behave as intended when it is called, the results may vary between compilers, etc etc.

    Within the dark and dingy details of some libraries that are shipped with some compilers, such techniques are sometimes employed. Such techniques effectively guarantee that the code is not portable to other compilers. Such techniques have also been known to break between versions of the supported compiler -- generally causing great frustration for users of the offending libraries.
    Last edited by grumpy; 09-11-2007 at 02:00 PM.

  7. #7
    Registered User
    Join Date
    Jun 2007
    Posts
    99
    aforementioned code snippets do not regard the restrictions ... I dont want to create objects of A

    I was thinking in terms that ... since member functions are not saved on per instance basic... they might have been allocated some area of memory during loading of the class

    So what if I could use a pointer to member function to save that address and use it to invoke a call to foo() from bar() ... without creating object for A

    ofcourse I would need an object for B to call ... but I am allowing that

    and I forgot to mention ... yeah the member functions can be public

    Code:
    #include<iostream>
    using namespace std;
    
    class A;
    
    void (A::*p)() = NULL; 
    
    class A
    {
          public:
                 
          void foo()
          {
               cout<<"A";
          }
    };
    
    class B
    {
         public:
                
          void bar()
          {
               p = &A::foo;
               A a;                     // I dont want to create object of A
               (a.*p)();               // calling requires object
          }
    };
    
    int main()
    {
        B *b = new B();
        b->bar();
        cin.get();
    }

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    What you are trying to is undefined - using undefined behaviour is generally going to cause something to go wrong at some point or another.

    What are you ACTUALLY trying to do - if you explain what your end goal is, maybe someone can come up with a good solution - right now you are asking "How do I loosen a wheelnut", when what you really should ask is "I've had a puncture, how do I change to the spare wheel".

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    A *x = (A *)0;
    x->foo();
    Please do not do this. Standard C++ provides plenty of safe valid mechanisms for your purposes.

    Let's get back to the original question.
    Code:
    class A
    {
         void foo()
         {
    
         }
    };
    
    class B
    {
         void bar()
         {
    
         }
    };
    If you want to call A::foo() from B::bar() you can make A::foo() public or make B a friend of A which I don't highly recommend. But you have to create an object of type A otherwise A::foo() does not exist. Then you can either pass a reference to an object of type A to B::bar() or you can pass a pointer of type A to B::bar(). Then you can call A::foo().

    One way of doing it.
    Code:
    class A
    {
      public:  
         void foo()
         {
    
         }
    };
    
    class B
    {
         void bar(A* ptrA)
         {
            ptrA->foo();
         }
    };
    Why would you want to call a function in A without creating an object of type A? This makes no sense.
    Last edited by VirtualAce; 09-12-2007 at 03:05 AM.

  10. #10
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    You need an instance to call a non-static member.

    Code:
    void foo() {
      std::cout<< "A::foo() method called\n";
    }
    
    class A {
    private:
    
    public:
    
    };
    
    class B {
    private:
    
    public:
      void bar( void ) {
        foo();
      }
    
    };
    
    /* ... */
    
    int main( void ) {
      A a;
      B b;
    
      b.bar( a );
    
      return 0;
    }
    Why not just have it as a separate function?
    It seems to me that if you want to be able to call a function within class two but not have an instance of class one from which to call it the function doesn't need to be in class one at all.

  11. #11
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    There's basically just 2 options.
    1. If foo() needs access to any non-static members of class A, then you MUST create an instance of A.
    2. If foo() doesn't need access to non-static members of class A, then it should be static, which would allow you to call it without creating an instance of A.

    Code:
    class A
    {
    public:
        static void foo();
    };

  12. #12
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Bubba View Post
    Please do not do this. Standard C++ provides plenty of safe valid mechanisms for your purposes.
    If you read my post again, you'll see I was certainly not advocating doing this.

    Given the requirements stated in the original post (calling a non-static member of a class without having an instance of that class), the only possible solutions invoke some form of undefined behaviour -- which is something I never advocate as it is not in the category of "safe valid mechanisms". But, it is appropriate to note the technical possibility -- particularly one that is actually employed within implementations of standard libraries associated with some well known compilers (compiler vendors are allowed to implement a specific interpretation of any form of undefined behaviour).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. minix system call pls help for project
    By porvas in forum Linux Programming
    Replies: 2
    Last Post: 06-14-2009, 02:40 AM
  2. C++ Classes: Use, Misuse...Confusion.
    By Snorpy_Py in forum C++ Programming
    Replies: 4
    Last Post: 10-23-2006, 01:46 AM
  3. Multiple types in lists, vectors or arrays.
    By megatron09 in forum C++ Programming
    Replies: 20
    Last Post: 08-31-2006, 01:54 PM
  4. C system call and library call
    By Coconut in forum C Programming
    Replies: 6
    Last Post: 08-22-2002, 11:20 AM
  5. Sharing a variable between classes of different .CPP files
    By divingcrab in forum C++ Programming
    Replies: 5
    Last Post: 07-07-2002, 02:57 PM