I know with pointers you can do this:
T * myPtr = 0;
which sets the pointer to a NULL value. However, when I try to do this:
T * myPtrArray[2] = {0, 0};
I get the "expected expression" syntax error. Why?
Note, I'm using g++ and the code above occurs in a class constructor:
template <class T>
RBTree<T>::RBTree() {
m_Data = T();
m_Children = {0, 0};
m_Parent = 0;
m_Color = BLACK;
}
where the class members in question are declared as:
T m_Data;
RBTree<T> * m_Children[2];
RBTree<T> * m_Parent;
bool m_Color;
-
2What compiler? Works for me with g++, clang and msvc.user703016– user7030162015年10月14日 05:24:02 +00:00Commented Oct 14, 2015 at 5:24
-
1It should work. Any context?yzn-pku– yzn-pku2015年10月14日 05:28:13 +00:00Commented Oct 14, 2015 at 5:28
-
Please show the actual error message.Jonathan Potter– Jonathan Potter2015年10月14日 05:37:33 +00:00Commented Oct 14, 2015 at 5:37
-
That's assignment, not initialization. There's a difference. Arrays don't support assignment.Jonathan Potter– Jonathan Potter2015年10月14日 05:42:13 +00:00Commented Oct 14, 2015 at 5:42
-
I thought that because it's in the constructor it would be considered initialization. Is this wrong then?Woody1193– Woody11932015年10月14日 05:43:00 +00:00Commented Oct 14, 2015 at 5:43
2 Answers 2
The form T * myPtrArray[2] = {0, 0}; is called aggregate initialization. It has no counterpart in assignment, so writing
T * myPtrArray[2];
myPtrArray = {0, 0};
is invalid.
In the case of class construction, aggregate initialization is unavailable in c++98/03.
If your compiler supports c++11 standard, you can use uniform initialization syntax. There are two ways to initialize m_Children in your example:
#1
In constructor:
template <class T>
RBTree<T>::RBTree(): m_Children {0, 0} /* other init here */ {
}
#2
During class member declaration:
T m_Data;
RBTree<T> * m_Children[2] {0, 0};
RBTree<T> * m_Parent;
bool m_Color;
2 Comments
m_children() is, and is probably the better option because ti does not depend on the number of elements in the array.As of C++11, you can use nullptr instead of 0. Using nullptr is preferred, as it is a pointer instead of an integer. Then, you could do:
T * myPtrArray[2] = {nullptr, nullptr};
Anyway, your code works fine on my compiler, you can see an example using both 0 and nullptr that compiles without errors on ideone.