How to check null class in C++
How do I check if a class is null or not in C++? Suppose I have class Line:
Line line; if (line == NULL) cout << "NULL"; else cout << "NOT NULL";
I get this error message:
no match for 'operator=' in 'line[i] = 0'
creates 1000 Line objects and stores them in the line array. The test against NULL makes no sense. You could define
In that case you need to initialize the array and your test would work.
I am guessing you are from a .NET or Java background. An object of class type cannot be NULL in C++. If you stored an array of pointers to Line, it would be another thing and your syntax would be valid.
Now, if you have your own semantics as to what a NULL Line is , you can
- Implement a member function called IsNull()
- Overload the operator void* and check if(Lines[i])
Pointer to an instance can be NULL not class instance.
Your Line class is not NULL. You have 1000 instances of Line, created by the default constructor. Arguably, you could test NULL using Line & operator == (const int ) const, and then compare some internal members, but that is odd to do it that way.
Line is not pointer . Whenever you writes. Line line;
1000 of line get allocated.
So after that line not be NULL.
Section 5.17 of the ISO standard says
There are several assignment operators, all of which group right-to-left. All require a modifiable lvalue as their left operand, and the type of an assignment expression is that of its left operand. The result of the assignment operation is the value stored in the left operand after the assignment has taken place; the result is an lvalue.
It is because the overloaded operator for the '=' does not match any of your provided overloaded instances.
You need to initialize it as Line * not simply Line and it should work. Better if you overload void* (e.g. new).
To answer your question, line has the type Line&, which can be read as a reference to a Line object. In C++, references cannot be NULL.
The error message in your question appears to be from a line of code that you have not posted. I can only speculate based on the error message that you are attempting to assign the value 0 to the line object located at index i. Because the = operator is not overloaded in your Line class, the compiler is unable to resolve the difference in types.