Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning general classes as null in C++

I am having kind of a trouble adapting a program from C# to C++. It’s very commom given a class to assign it the null value. But C++ is not accepting the equivalent form ‘nullptr’

class Point{
     public:
         int x,y;
}
//...
Point p = nullptr;

There is some way of solving it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot assign nullptr to a class because a class is a type and not a variable. What you’re doing by typing Point p = nullptr; is that you’re asking the compiler to find a constructor of Point which accepts a nullptr.

You can either create an object of Point as an automatic variable by doing this:

Point p = Point{1, 2}; // sets x = 2 and y = 3

or simply like this:

Point p;

for which however you will need to define a constructor which initializes x and y because you haven’t provided the member variables with default values.

Depending on the context in which this statement resides, p will either be allocated on the heap or on the stack. In case you’re instantiating p in the main function, it will be the latter.

You can create a pointer to an object of Point by doing this:

Point* p = nullptr;

However, you will only have created a pointer. You will need to further take care of allocation, which you can do like this:

Point* p = new Point{1, 2};

in which case you should also free the allocated memory before your program ends like so:

delete p;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading