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

is it a good practice to use nullptr as None as in python in c++

I’m building a program with c++, but I’m not sure if this way is right.

class A {
  private:
    unsigned *a;

    bool checkA() {
      return a != nullptr;
    }

  public:
    A() {
      this->a = nullptr;
    }

    void setA(unsigned a) {
      this->a = new unsigned(a);
    }
}

The member variable ‘a’ will only be set by ‘setA’, however in other method, I have to check if ‘a’ has been set. Thus I used nullptr to check if it is set.

Is this code a good practice?

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

I tried to change the datatype of ‘a’ to int and set it to -1 to notice for an uninitialized value. However I think there would be a better way to do this.

Please give me some advices.

>Solution :

You could use std::optional<int> if you really want.

But setA itself is an anti-pattern, just set the value in the constructor, RAII is your friend, not something to actively avoid.

It is much easier to reason about the code if a is always present than A being stateful with sometimes having a, sometimes not.

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