qkflies
qkflies

Reputation: 31

error: "null" was not declared in this scope

I am at my wits end trying to debug the above error. I am providing my code below to assist with the troubleshooting process:

#include <string>
using namespace std;

class Packet
{
    int index;
    string content;

    public:
        Packet()
        {
            index = null;
            content = null;
        }

        Packet(int i, string data)
        {
            index = i;
            content = data;
        }

        void setIndex(int i) {index = i;}
        void setContent(string input) {content = input;}
        int getIndex() {return index;}
        string getContent() {return content;}
};

I have tried adding #include <cstdlib> (from here), #include <cstddef>, and manually defining null. Nothing has succeeded. If you can shed light on what I am missing, that would be greatly appreciated.

Upvotes: 0

Views: 8652

Answers (2)

Tom
Tom

Reputation: 7992

I suggest you read up on memory management in C++.

To take a small sample of your code:

class Packet
{
    int index;
    string content;

    public:
        Packet()
        {
            index = null;
            content = null;
        }

index and content are not pointers or references, they are values; it makes no sense to assign null to them.

int index declares an integer variable called index; the only values it can take are numbers in the range representable by int on your platform (most likely a 32-bit signed number).

Similarly, string content declares a string object, complete with the memory to hold it. It must be constructed (in this case in the Packet class constructor). It makes no sense to try to assign a 'null' value to it.

I'd guess that you are used to writing Java code, where object variables are always references and so can be assigned null; that is not true in C++.

The concept of 'null' is a pointer to nothing; in C++ this is written nullptr (in C++11) or 0 (in earlier C++ standards); it is common to #define NULL 0 in those earlier versions.

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754640

You probably want to write:

    Packet() : index(0), content("") { }
    Packet(int i, string data) : index(i), content(data) { }

The word null is not reserved by the C++ standard. NULL is a null pointer constant, but is not appropriate as an initializer for int (you might get away with it, but it would be equivalent to writing 0, and it is bad practice to use NULL where you mean 0 or '\0'), and it is not really appropriate to initialize a string with NULL either.

You could even use:

    Packet(int i = 0, string data = "") : index(i), content(data) { }

to have a single constructor with defaulted arguments.

Upvotes: 1

Related Questions