When using encapsulation and "tell, don't ask"-principle properly, there should be no reason for one to ask information from an object. However, I've ran into a situation (let me know if this design itself is terrible) where I have an object with a member variable pointing to a function outside of the class.
At some point of my application, there's a need for my object to call the function and the function should then act based on my object's status.
Here's an example class:
typedef void(*fptr)(Foo*);
class Foo {
public:
Foo(string name, fptr function);
void activate()
{
m_function(this);
}
private:
string m_name;
fptr m_function;
};
That's the class, now the developer can use the class like so;
void print(Foo *sender)
{
cout << "Print works!" << endl;
}
int main(int argc, char **argv)
{
Foo foo("My foo", &print);
foo.activate();
// output: "Print works!"
}
This all works fine, but what if I want to print the name of the sender?
All the functions are defined outside of the class, by other developers, so there's no way to access private variables.
In C#
, you can just use the partial
keyword to add a method to an existing class.
This is not possible in C++
though.
I could just ignore encapsulation and create a setter and getter for name
and all other properties that might be needed by the function in the future.
This is pretty terrible solution, I should basically create setter and getter for everything there is in my class, since the function can do anything to my object.
Besides what's the reason of encapsulation, if I'm just gonna ignore it when I want to?
An other solution would be a struct that holds the required properties inside it:
struct FooBar {
string name;
};
typedef void(*fptr)(FooBar);
void Foo::activate()
{
FooBar fb;
fb.name = m_name;
m_function(fb);
}
But this is not much different from not using encapsulation, and it doesn't seem like a too good solution either. What would be the best approach for this problem?