Reputation: 619
I am trying to compile some old source code from another person in my lab. And I cannot really understand the idea of the following trick. Why somebody wants to access CLog2Factory class trough the reference given by gLogFactory()? And how can I successfully compile and link the code below?
The whole code is big, so I made a short example. Keep friend and virtual as they present in original code.
test.h:
class CLog2;
class CLog2Factory
{
friend class CLog2;
public:
CLog2Factory() {}
virtual int init() = 0;
};
CLog2Factory& gLogFactory();
class CLog2
{
public:
CLog2() : gLogFactory().init()
{ }
};
test.cpp:
#include "test.h"
int main(int argc, char *argv[])
{
CLog2 log;
return 0;
}
I get the following error:
test.h: In constructor ‘CLog2::CLog2()’: test.h:50:15: error: class ‘CLog2’ does not have any field named ‘gLogFactory’
CLog2() : gLogFactory().init()
^
test.h:50:28: error: expected ‘{’ before ‘.’ token
CLog2() : gLogFactory().init()
In fact, I could compile the original code (perhaps I am missing something in my test example). but couldn't link it. Error from linking of original code is the following(file test.h is changed to Log2.h now):
Log2.h:254: undefined reference to `gLogFactory()'
Upvotes: 0
Views: 164
Reputation: 23793
Your code is missing something from the original : a member (which as the type returned by the init()
method) is initialized by this initialization list, something like :
class CLog2
{
public:
CLog2() : x(gLogFactory().init())
{ }
int x;
};
Upvotes: 2