I have some class Foo and Logger:
class Logger{/* something goes here */};
class Foo{
Foo(Logger& logger);
Logger& logger;
}
Foo::Foo(Logger& logger) : logger(logger)
{}
Now I want to create an array of objects of class Foo, where all references Foo::logger
should point to the same Logger
object. I tried something like (I need both stack and heap allocation):
Logger log (/* parameters */);
Foo objects [3] (log); // On stack
Foo* pObjects = new Foo [3] (log); // On heap
The problem is that both versions try to call the default constructor Foo()
which is not present. Also as I understand it is not possible to change the referenced variable of a reference. So a temporary call to the default constructor and a later initalisation in a loop does also not help.
So: What is the right way to do it? Do I need to use pointers to the Logger
object?
An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.
C arrays are declared in the following form: type name[number of elements]; For example, if we want an array of six integers (or whole numbers), we write in C: int numbers[6];
To reference a particular element in an array, specify its row and column number using the following syntax, where A is the matrix variable. Always specify the row first and column second.
Arrays are effectively passed by reference by default. Actually the value of the pointer to the first element is passed. Therefore the function or method receiving this can modify the values in the array.
You cannot initialize an array of objects with non-default constructor. However you can use a vector as shown here (Look at the first reply)
And for the heap you can do the following :
Foo* pObjects[3];
for (int i = 0; i < 3; ++i) {
pObjects[i] = new Foo(log);
}
For general uses I normally make a logger a Singleton so there is only one and can be accessed from all components. http://en.wikipedia.org/wiki/Singleton_pattern
This also makes the constructor of Foo much simpler.
class Logger
{
public:
static Logger& getInstance()
{
static Logger instance;
return instance;
}
public log(const std::string& txt)
{
//do something
}
private:
Logger() {}
Logger(Logger const&); // Don't Implement.
void operator=(Logger const&); // Don't implement
};
And use it in Foo like:
Logger::getInstance().log("test");
or
Logger& logger = Logger::getInstance();
logger.log("test");
(Credits for singleton from @Loki Astari : C++ Singleton design pattern )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With