Can a static member function access non-static member?

D

dolphin

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

Ian Collins

dolphin said:
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?
 
P

Pete Becker

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
}
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top