Reputation: 329
My goal is to use a class inside another class, this would reduce the overall code and improve readability. There is one class that accesses the hardware, and other classes should make use of this class
Here is the harware class:
class NFC:NFC(int buspin, int datapin, int resetpin, int cspin, int *param)
inside the class is:
NFC::getDatablock(uint8_t address, uint8_t *data);
Now there are classes "configuration" and "history" that need to read and write data from the NFC class.
Currently my solution is as following:
NFC reader(1,2,3,4,x);
CONFIG configuration();
//read configuration from reader
uint8_t configuration[64]={};
reader.getDatablock(3, &configuration);
//transfer data to config:
configuration.importData(&configuration);
//save data
uint8_t newData[64])={};
configruation.getdata(&newData);
//transfer to reader
reader.write(1,&configuration
This requiers to add this code in the "main" application, because main.cpp knows about all the classes. It would be more desirable if it would be possible to just call :
configuration.getConfig();
and inside the function:
void configuration::getConfig(){
uint8_t db[64] = {};
reader.getDatablock(3, &configuration);
...
}
Its there a way to achieve this?
Upvotes: 2
Views: 342
Reputation: 455
There are two Options:
Option 1:
You will create a private variable in the Configuration class of type Reader, then add a parameter in the Constructor of the Configuration class that accepts a Reader instance. You can then assign this instance to the private instance variable in the Configuration class.
Then in Configuration::getConfig()
you can access the Reader instance through your Private Instance Variable.
Configuration.h
Class Config {
public:
Config(Reader *reader);
void getConfig();
private:
Reader *_reader;
Configuration.cpp
Config::Config(Reader *reader){
_reader = reader;
}
void Config::getConfig(){
...
_reader.getDatablock(...)
...
}
Option 2:
As stated by @mcabreb you can just send through the reader instance as a parameter in getConfig()
Config.h
Class Config{
...
void getConfig(Reader *reader);
Config.cpp
void getConfig(Reader *reader){
...
reader.getDatablock(...)
...
}
Upvotes: 2