A
A
Andrey Yanduganov2016-09-14 10:31:17
C++ / C#
Andrey Yanduganov, 2016-09-14 10:31:17

Override operator() to access class member?

Let's say I have such a class (I removed everything superfluous for clarity):

class Window{
public:
  Graphics *g;
}

For example, I create somewhere In order to call the function of the g object, I need to write tediously and only then write the desired function. This is bad at least because my g can be easily changed outside the class. But making it private is not a good idea, because then you have to write some kind of layer to call each function, and there are about a hundred of them, and even all with overloads. And I thought: is it possible to somehow cleverly redefine operator () so that these lines are equivalent:Window myWindow();myWindow.g->

myWindow.g->Clear(Color::White);
myWindow(Clear(Color::White));

That is, roughly speaking, to forward the methods of the g object to your class. Is it real at all? Well, or at least something similar, so that the code is more secure and compact.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2016-09-14
@andreybotanic

Maybe you'd be fine with inheriting your Window from Graphics?
The effect of inheritance is exactly what you want to get in other ways.

M
Mercury13, 2016-09-14
@Mercury13

class Window{
public:
  Graphics& operator * () const { return *g; }
  Graphics* operator -> () const { return g; }
private:
  Graphics *g;
}

...

window->Clear(Color::White);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question