2

I'am new with c++ and pointers and I have a problem with this c++ code. Normally this code must display "true" but it doesn't. Thanks in advance.

class Trie{  
   public:
      Trie* root;
      int color;
      Trie(){
         color=0;
       }
       ~Trie(){
       }
  };

 int main(){
   Trie test;
   if(test.root==nullptr)cout<<"true"<<endl;
  }
med amine
  • 33
  • 2
  • 5
    because you never set it to `nullptr`. in the constructor after `color = 0;` , write `root = nullptr;` – Arash Mar 08 '17 at 01:22
  • 6
    You never initialized `test.root`, what did you expect to happen when you wrote `test.root==nullptr` ? – M.M Mar 08 '17 at 01:23
  • 2
    Since your constructor does not initialize root, it can be anything at all. – user31264 Mar 08 '17 at 01:25
  • Note that whitespace is your friend. Your `if` statement is very hard to read without any spaces. – Dai Mar 08 '17 at 01:27
  • If you expect `int` to be a 32-bit integer you're mistaken (on some platforms `int` is 16 bits!). If you need a 32-bit integer to store a tuple of 0-255 RGB values then you should use an explicit `uint32_t` or better yet: define a tuple struct which holds 3x `uint8_t` values. You'll also get better performance because the members will be processor-word aligned. – Dai Mar 08 '17 at 01:31
  • This isn't the problem, but don't use `std::endl` unless you need the extra stuff that it does. `'\n'` ends a line. – Pete Becker Mar 08 '17 at 01:33
  • The question [Does C++ default-initialization preserve prior zero-initialization?](http://stackoverflow.com/q/33456141/1708801) is similar and as noted there default-intialized objects will have indeterminate value if not initialized. Using indeterminate values is undefined behavior. – Shafik Yaghmour Mar 08 '17 at 04:38

1 Answers1

9

C and C++, unlike Java and C#, do not automatically zero-initialize memory or object members for performance reasons as there's no point overwriting memory twice if you're just going to set your own value anyway; the downside is you have to be very careful to ensure you don't use uninitialized data first.

To fix your problem, you can either set the member in the constructor, or in the initialization list:

Trie() {
    this->color = 0;
    this->root  = nullptr;
}

Or:

Trie() :
    color ( 0 ),
    root  ( nullptr )
{    
}

As for your color value, consider using a tuple instead because there are no guarantees that int will be a 32-bit integer (assuming you need to store 0-255 RGB values):

struct RgbColor {
    uint8_t r;
    uint8_t g;
    uint8_t b;

    RgbColor() :
        RgbColor( 0, 0, 0 ) {
    }

    RgbColor(uint8_t r, uint8_t g, uint8_t b) :
        r(r),
        g(g),
        b(b) {
    }

    RgbColor(uint32_t rgb) :
        r( ( rgb >> 24 ) & 0xFF ),
        g( ( rgb >> 16 ) & 0xFF ),
        b( ( rgb >>  8 ) & 0xFF ) {
    }
}
Dai
  • 141,631
  • 28
  • 261
  • 374