Cannot initialize object in member initialization list
I have this code:
CCalcArchive::CCalcArchive() : m_calcMap()
{
}
m_calcMap
is defined as follows:
typedef CTypedPtrMap<CMapStringToPtr, CString, CCalculation*> CCalcMap;
CCalcMap& m_calcMap;
When I compile in Visual Studio 2008 I get this error:
error C2440: 'initializing' : cannot convert from 'int' to 'CCalcArchive::CCalcMap &'
I don't even understand where he gets the "int" error, and also why it doesn't work? It looks like I have some sort of syntax error, but isn't that how member initialization lists are supposed to be? Also, AFAIK, the MFC class CTypedPtrMap
does not have a constructor that takes arguments.
source to share
int
comes from CTypedPtrMap
having a constructor that takes an argument int
which defaults to 10.
The real problem you are having is that in the initialization of links m_calcMap
you have a default attempt to create a temporary object CTypedPtrMap
to bind the link. However, only references const
can bind to temporary objects. Surely the error message is not very informative.
But even if the member m_calcMap
was const
refernce, you still have the problem of binding to temporary. in this case, the MSVC 2008 compiler gives a pretty clear warning:
mfctest.cpp(72) : warning C4413: '' : reference member is initialized to a temporary
that doesn't persist after the constructor exits
source to share
I'm not sure where it is getting from int
, but you have to initialize all references in the initializer list. m_calcMap
is declared as a reference, so it must be initialized to refer to some instance of the object CCalcMap
- you cannot leave it uninitialized. If you fail to pass a referencing object to the constructor, or there is a chance that you need it not to refer to an object, then use a pointer instead of a pointer.
source to share
This is a common protocol for C ++ compilers when they can't figure out what a type is, spit out an error message, and assume the user meant "int" in order to be able to continue (... and generate even more error messages ; -)
You need to initialize all references in the class in your constructors.
source to share
Ah, yes, my idea was that I intended to run my constructor on the initializer list and thus the object must always be constructed. It is getting clearer now, especially after Mike B's answer, and it now makes sense that a constructed object will be destroyed immediately after going out of scope. This is what I never looked at first.: S I thought it was ok with references and also initialize it with a reference to an existing object.
source to share