Monday, March 17, 2008

const Programming

Related to my last post about the professor calling out my sluff discussion tactics, it made me really gung-ho for week two. So much so I bothered a co-worker, a mastered programmer/computer science guy, about some the intricacies of programming. It happened to be one of the discussion topics, which I was gladly able to expand upon. The topic, const in relation to member functions of a class.

I've seen const used multiple ways, here's a good example I'll try to explain:

//assume this function exists in a class that contains an
// important formated message string and you want to get
// a specific argument (like the 10 entry) within that string
const char* getMsgArg(int nArg, const char* sCharString) const;

The first const means that any variable assigned to the return value of this function can't be changed. For instance, say the object is called myMessage and you access this function by myMessage.getMsgArg(10);. The const at the front means you can't change this. This may seem a little fuzzy, but what is really returned in a pointer. So the const means that the pointer that is myMessage.getMsgArg(10) can't be changed (such as setting it to NULL or 0 or worse, a different pointer.)

The const on sCharString means that sCharString cannot be changed inside the function. The reason you would need this is because its a pass by reference, not by copy. In this case, the int is safe because its a copy, but the char string isn't, its a reference, an address.

The const at the end means that the function cannot change member variables. Like Josh said, it stops unintended consequences inside the function. I think the compiler will warn/error if you try (purposefully or not) to change member variables.

Readers, please correct me if I'm wrong in anyway, I'm just a student after all.


1 comment:

Gail said...

I must be an idiot.