Problems with non static variables in a class

Started by
5 comments, last by rip-off 12 years, 11 months ago
Hi guys,

I am having a problem with a varible (a Socket) within a class.

At compile time it says "illegal reference to non-static member"

If I make the variable static, it compiles ok but then gives linker errors.

Any ideas on what is going wrong would be awesome :)
Advertisement
Post the code that's causing the compile time error.

Sounds like you're trying to access the member without actually having an instance of the class, such as from a static member function.

I am having a problem with a varible (a Socket) within a class.

At compile time it says "illegal reference to non-static member"

If I make the variable static, it compiles ok but then gives linker errors.


For the linker error, you're probably missing the definition of the variable in your .cpp file:


// header file
struct T {
static Socket* socket;
};

//in the .cpp:
Socket* T::socket;
So, the definition needs to go in the CPP file and not in the Private: part of the class?
With static class members, both, as jmastro demonstrated.

However, there's a huge difference between a regular class member and a static class member! Do you want your variable to only ever have a single instance, or do you want one instance of the variable per object? What are you trying to do?
Just a single instance that can be used class-wide.

I am using a Socket instance where a public function within the class calls up a function that performs a socket read. The socket read is multi-threaded - so it will poll away.

So, currently (since starting ths post) I have declared a socket in the private: part of the class and have made a reference to it by putting SOCKET *pSocketClient; in the CPP file and copying the private socket to *PSocketClient in the constructor.

Is that an ok way to handle the problem?

Is that an ok way to handle the problem?


Erm, probably not. Sounds a bit confused. jmastro has already posted the correct way to declare and define a static class member.
It is a superior solution to a global/static variable (mostly).

If you just are using the socket for one or two functions you might make it a parameter to those functions. It depends on what T is, some objects have no business holding a reference to such I/O handles.

This topic is closed to new replies.

Advertisement