Funky Monkey Software | Development, Applications and Chimps

Archive for February 28th, 2011

Its been a while since I worked with C++ (a few months at least) and even when I did use the language, I was looking at it from a Java developer's perspective rather than trying to understand what the language is all about. My Computer Science lectures on C++ and different programming paradigms has really opened my eyes as to how C++ should be used (separately and in different ways to Java).

The first lesson I've been learning is about 'Constness', that is, declaring things that don't change constant in your programs to ensure that the compiler tells you when you try to change them and thus, iron out silly bugs. An example of this is as follows:

You may define a cat class in your program. Logically, you would never wish to change the gender of a cat, So the cat's gender could be declared a constant:

cat.h:
class Cat{
...
private:
      const bool isMale;
...
}
cat.cpp:
Cat::Cat(bool male) : isMale(male){
...
}

Now, you want to see if two cats have the same  gender, but you put in a typo:

Cat::canBreed(Cat otherCat){

    if(this->isMale = otherCat->getIsMale()){
          return false;
    }

}

Sad kitteh is sad: "Why you trying to reassign mah gender?"

You wanted to compare the gender of the two cats, but instead, you are trying to assign the gender of Cat A to the gender of Cat B. Luckily, the C++ compiler will help you out here.

Since you declared isMale as a const, this typo will be singled out as a mistake and the compiler will tell you that you are trying to do something wrong: this is a good thing!

So what about mutables? These are a slightly more difficult concept to grasp, but essentially they are only to be used when the object does not logically change, but must change in practice. For example: For loading an image just in time, rather than keeping it in memory (the image 'object' remains the same, but the image data buffer itself changes at the last minute). I stumbled across this article on mutables, and I couldn't have put it better myself.

So that's all for the first in my series of exciting C++ adventures, No cats were psychologically or physically damaged in the making of this article.

· · · · · ·

Theme Design by devolux.nh2.me