Regarding Reference variable
-
Hi all, I have a reference variable in my class. I need to initialize it in the constructor. But, the compiler is giving an error. Can any one help me out from this problem?
Reference member variables must be initialized in the constructor's initialization list, for instance
class A
{
int & iRefNum;public:
A(int & i): iRefNum(i)
{
// whatever
}
};:)
If the Lord God Almighty had consulted me before embarking upon the Creation, I would have recommended something simpler. -- Alfonso the Wise, 13th Century King of Castile.
This is going on my arrogant assumptions. You may have a superb reason why I'm completely wrong. -- Iain Clarke -
Hi all, I have a reference variable in my class. I need to initialize it in the constructor. But, the compiler is giving an error. Can any one help me out from this problem?
You've to initialize it in constructor initializer list. For e.g.
MyClass::MyClass( CString& myString )
: m_StringReference( myString )
{
// Assume m_StringReference is a reference declared in class.
}regards, Jijo.
_____________________________________________________ http://weseetips.com[^] Visual C++ tips and tricks. Updated daily.
-
Hi all, I have a reference variable in my class. I need to initialize it in the constructor. But, the compiler is giving an error. Can any one help me out from this problem?
kuttiam wrote:
I need to initialize it in the constructor. But, the compiler is giving an error.
You should initialize a reference variable in the constructor initialization list e.g.
class MyClass
{
public:
MyClass( int& RefVal ) : m_RefVal( RefVal ) // Ok
{
m_RefVal = RefVal;// Error, cannot do this here
}private:
int& m_RefVal;
};Since a reference variable is much like a constant var it must be initialized like a const var. i.e. initialize where it's declared and in classes we cannot initialize where it's declared hence initialization list is provided.
Nibu thomas Microsoft MVP for VC++ Code must be written to be read, not by the compiler, but by another human being. Programming Blog: http://nibuthomas.wordpress.com
modified on Wednesday, May 28, 2008 5:10 AM