Why use const?

Started by
7 comments, last by Leadorn 18 years, 1 month ago
when do I use const? and what is the difference between declaring a class like this: Mammal Dog; vs. Mammal = new Dog; Thank you.
Advertisement
The "new" operator is used when working with pointers.
why use pointers?
I'm guessing only to avoid the chances of repetitive programming?
and to throw and contain object around?
Mammal Dog

is allocating memory for the object on the call stack of the function that you are doing it in.

Dog = new Mammal is allocating memory from the heap and will return to you a pointer to that heap memory address. The actual syntax for this operation is.

Mammal* Dog = new Mammal
Use const when the value will never change:
Quote:
const int FPSLimit = 60;

When you use 'new', you must delete it, because it is created at runtime instead of compile-time:
Quote:
Baddy = new Enemy;...delete Baddy;
when you do something right, people won't be sure you've done anything at all.
Take a look at this page for information on 'const'. For 'const correctness', take a look at this page. Hopefully between those two pages your first question will be answered.

On the issue of pointers, take a look at this page to learn about them. GameDev has an article you might want to check out as well here. It ties in the why you would want to use pointers in games and such. Between those two pages, hopefully your second question will be answered [smile]
EDIT: Zoinks. Please ignore - I am a lot more confident in Benton's links than in myself. :)
It only takes one mistake to wake up dead the next morning.
Quote:Original post by oscinis
When you use 'new', you must delete it, because it is created at runtime instead of compile-time:


This is not true. "Mammal Dog" is not created at compile time. It is created while the function is executing at run-time. It is destroyed before the function returns to the calling function. If "Mammal Dog" is written outside a function, Dog is created before main() is run and destroyed after exiting main().

The difference is that "new Mammal" is created on the heap wherease "Mammal Dog" is created either on the stack (when in a function) or in a data segment (when declared at file-scope). And if you allocate it on the heap, yes you are correct, you should delete it.
Const is good but can be hell if it isn’t used throughout the hole project.

Declaring a variable const lets the compiler do optimizations. It doesn’t need to get the value from the source. So if it the same value stored closer it can use it instead. There is also something called Volatile its not the exact opposite but almost.

This topic is closed to new replies.

Advertisement