I’m reviewing some code and I have stumbled many times on examples as described in title. THen this passed object is referenced in calling outside methods from second object, even changed somewhere else and then again used by reference in another methods.
THe weirdest thing is that the second object calls methods from passed first object that created second anyway.
I haven’t done similar stuff yet, but I since I am relatively new to C++ I allow possibility that people feel very free in coding with language with so many options…
However, the main question is: is that common practice? Is there any technical reason for not doing such stuff?
I have added a short example:
TypeReturned *ClassB::GetSomething( ClassA *objectA)
{
someMethod(wm);
ClassC *objectC = new ClassC(objectA->method());
PCS->method(……, &objectA->someMethod(), objectA);
}
This method is called from objectA.
First call is quite normal. The second and the third would be more readable to solve with simpe passing needing parameters, not the complete classes and callbacks.
I can also say, that those those 2 classes do not really communicate to each other and don’t have cross-references.
It is both usual and practical. Quite often it’s the most natural way to achieve something. For example if you want a parent-child navigable from both ends, it’s easiest for the parent object to pass itself (
this) to the child object after creation so that it stores the reference to parent. Registering self for callback (as in the observer pattern) is another example.This is useful in general, not something specific to C++.