Reputation: 7960
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;
Upvotes: 0
Views: 679
Reputation: 1082
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:
In constructor:
template <class T>
RBTree<T>::RBTree(): m_Children {0, 0} /* other init here */ {
}
During class member declaration:
T m_Data;
RBTree<T> * m_Children[2] {0, 0};
RBTree<T> * m_Parent;
bool m_Color;
Upvotes: 1
Reputation: 533
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.
Upvotes: 0