currently I switch from Java to C++ and this is giving me a hard time (but lots of new experience ^^). I’m writing some data-transfer-objects which contain configurations for my program. I’ve written some classes and now I want to have a class which behaves like a container.
Here’s a header for the container:
class MyContainer{
public:
MyContainer();
virtual ~MyContainer();
Config getConfig(TypeEnum type) {
switch (type) {
case ATYPE:
return config_a;
case BTYPE:
return config_b;
default:
break;
}
}
ConfigA config_a;
ConfigB config_b;
};
The configs have some data in it and are derived from another config-file.
And here is the C++-Source:
MyContainer::MyContainer(){
ConfigA config_a(int c = 1);
ConfigB config_b(double b = 2.1);
this->config_a = config_a;
this->config_b = config_b;
}
There are several problems I think. But the main question for me is:
How can I get those configs in this container to share it to other modules of my program? I have tried to make config_a to a pointer but I always get error-messages that these types won’t match.
this->config_a = &config_a; //If ConfigA config_a; was ConfigA *config_a; instead
If you have another minute for me then please tell me if the getConfig-Method could work like this.
And if there’s another topic for this then please share. Thanks.
If you write
ConfigA configAin your header, the configA is automatically allocated during the allocation of the container class. So you don’t have to initialize it like following:Instead, you can just do the following:
There is no need to write:
In short words, the mentioned
int c = 1is an operation, which:To understand this, try the following:
If you want to pass the configs to another modules, you can choose one of the following solutions:
a) Accept the configs as references (the config classes have to derive from the same base class):
In this case, container shall return the configs in the following way:
But the header shall be modified:
b) Accept the configs as pointers (same as above)
In this case, container shall return the configs in the following way:
Finally, this is the way I would do it:
The const-correctness is also worth mentioning, but we’ll leave it as an exercise for the OP 😉