Can a static member function access non-static member?

Discussion in 'C++' started by dolphin, Dec 5, 2007.

  1. dolphin

    dolphin Guest

    Hello everyone! Can a static member function access non-static member?
    I think it is illegal.Is it right?
     
    dolphin, Dec 5, 2007
    #1
    1. Advertising

  2. On Dec 5, 9:27 am, dolphin <> wrote:
    > Hello everyone! Can a static member function access non-static member?
    > I think it is illegal.Is it right?


    Write a 10-line test program and see :)
     
    Ioannis Gyftos, Dec 5, 2007
    #2
    1. Advertising

  3. dolphin

    Ian Collins Guest

    dolphin wrote:
    > Hello everyone! Can a static member function access non-static member?
    > I think it is illegal.Is it right?


    Yes, provided it has a pointer or reference to the object. Why
    shouldn't it?

    --
    Ian Collins.
     
    Ian Collins, Dec 5, 2007
    #3
  4. dolphin

    Pete Becker Guest

    On 2007-12-05 02:27:21 -0500, dolphin <> said:

    > Hello everyone! Can a static member function access non-static member?
    > I think it is illegal.Is it right?


    Just like any other member function, it has access to private members
    of objects of its class. Just like any other member function, it can
    access those members through a pointer or reference to an object of its
    type. Unlike non-static member functions, it doesn't have an implied
    object to work with.

    class C
    {
    public:
    void member_func(C *ptr);
    static void static_member_func(C* ptr);
    private:
    int i;
    };

    void C::member_func(C *ptr)
    {
    ptr->i = 3; // access member of object pointed to by ptr
    i = 3; // access member of object pointed to by 'this'
    }

    void C::static_member_func(C *ptr)
    {
    ptr->i = 3; // access member of object pointed to by ptr
    }

    --
    Pete
    Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
    Standard C++ Library Extensions: a Tutorial and Reference
    (www.petebecker.com/tr1book)
     
    Pete Becker, Dec 5, 2007
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Victor Bazarov
    Replies:
    0
    Views:
    1,366
    Victor Bazarov
    Jun 23, 2003
  2. slide_o_mix
    Replies:
    0
    Views:
    424
    slide_o_mix
    Oct 15, 2003
  3. Alex
    Replies:
    0
    Views:
    393
  4. Assertor
    Replies:
    1
    Views:
    605
    Victor Bazarov
    Mar 9, 2006
  5. ittium
    Replies:
    5
    Views:
    443
    88888 Dihedral
    Jan 12, 2012
Loading...

Share This Page