A
A
Andrey Yanduganov2016-09-05 17:16:30
C++ / C#
Andrey Yanduganov, 2016-09-05 17:16:30

How to access private members of a class from a static method?

This is how a variable is declared in my class:

private:
  HDC hdc;

And here is the static method:
static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)

When in this method I try to refer to the mentioned variable like this
hdc = GetDC(hwnd);
, an error occurs "a non-static reference to a member must be specified relative to a given object" . How to access this variable? In Google, such an error occurs often, but in a completely different context, so I could not find anything similar.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
L
LittleFatNinja, 2016-09-05
@LittleFatNinja

no way

A
AxisPod, 2016-09-06
@AxisPod

You are trying to take a non-static member from a static method, which does not exist in nature without an object, but you don’t have an object. The problem here is not private. Throw a thread in some way into a static method object, and there already get it. Yes, and that's exactly what you wrote in the error.

R
Rou1997, 2016-09-05
@Rou1997

It doesn't matter if private members or not, whether they are static or not, if they are static like a method, then no problem, and if not, then either use the singleton pattern, etc., or access to memory (a low-level "trick", in fact the same singleton).

V
Vladimir Dubrovin, 2016-09-05
@z3apa3a

Static methods do not apply to a class object, they exist separately from objects and therefore do not have access to any non-static members of the class. If you want to use a property of a specific object, you must explicitly pass a reference to this object to a static method (which in general does not make sense, it is reasonable to make the method non-static)

K
Konstantin Stepanov, 2016-09-06
@koronabora

It is necessary to spread static methods and variables into different classes. In the class for variables, make wrappers for accessing them, and give this class with variables as a pointer to a static method.
Roughly speaking, class instances and static methods lie in different areas of memory. If even rougher, then static methods do not belong to any instance of the class, but, at the same time, are available in their scope to anyone.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question