Bill Roper (billroper) wrote,
Bill Roper
billroper

On classes and structs

When you create a class in C++, it will execute a constructor which allows you to automatically initialize all of the members to a known set of values. This is a good thing, because otherwise you will get whatever random garbage is sitting at the spot in memory. If other classes are members of the class that is being constructed, they will automatically call their default constructors so that they are properly initialized.

If you create a struct in C++, you must initialize it by hand. If the struct contains classes, their constructors will not be called automatically, so they will be filled with random garbage.

It is important to know this and apply this knowledge lest your application crash in interesting fashion.

Happily, I already knew this.

Update: And you can have a constructor for your struct in C++, so if you bother to write the constructor, you can do the initialization trivially, because then the default constructor for your classes will be called. I learn something new every day. :)

You still need to actually write the constructor though...
Tags: c++, computers, musings, work
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 3 comments