Messaging with composition
*EDIT: a better title probably may have been, "Messaging between objects"*
Suppose I have the following (please forgive syntax errors):
Code:
class Module {
public:
Component *getComponent(type) {
switch (type) {
case "whatever":
return new WhateverComponent();
break;
}
}
virtual String getModuleName();
}
class MyModule : public Module {
public:
String getModuleName() { return "MyModule"; }
}
class Component {
void getContent() {
...
// I want to call Module->getModuleName() here
...
}
}
class SubComponent : public Component {
...
}
Module module = new MyModule();
Component component = module->getComponent();
String content = component->getBody();
How do I get the module name (via getModuleName()) inside getContent() in Component to get the name associated with the Module subclass that instantiated the component?
Would a good approach be to pass a pointer or reference to the Module (using "this") in the Component constructor in getComponent() when instantiating the Component?
Code:
class Module {
...
Component *getComponent(type) {
switch (type) {
case "whatever":
return new WhateverComponent(this);
break;
}
}
...
}
class Component {
private:
Module *module;
void getContent() {
...
cout << this->module->getModuleName();
...
}
}
Any better approach(es)?