-
Re: C++ Class, Why?
Quote:
Originally posted here by Epison07
Ok, I am moving ahead in my C++ book. Because of this helpful tool, I have passed my programming class and have no one to turn to but the AO community. Now I am on classes. I kinda understand the syntax, for the most part. But what I cant see is where I would use this. I guess what I am trying to say is, what is the purpose? Where would you use classes. In the book it explains how to create and use them, but it only give and example about class Cat. So maybe someone can provide some information on what you use classes for. Are they just for good programming?
Also, while talking about C++ classes, I was wondering what the constructor and destructor does. I understand you would be like,
Cat::Cat()
and
Cat::`Cat \\Tilde
What are these and what do they do?
Thanks in advance.
-Ep
It is already pretty well explained, but:
A constructor. Exactly what it says it is. Since we are dealing with object oriented programming, every time you use a new object of this type, it can be initialized, by calling the constructor. The constructor essentially sets up all your default values, or performs whatever you need done to make sure your object is ready to use. Why do you need it? If you are following proper OOP guidelines, none of your variables will be directly set-able (they will be all typedef'd as private) to keep the object insulated from the rest of the code. If you can't set it directly, you must invoke methods in the object to set them. You can either call whatever set of methods you need to setup the object, or you can just call the constructor once...Big thing...constructors are called when the object first loads.
A destructor. Exactly what is says it is. The destructor is called every time the object needs to be unloaded from memory. It is not a big deal if you are using all static variables; however, when you get to more complicated programming that is using pointers (essentially references to blocks of memory), it is very important to properly cleanup after the object, otherwise you will get memory leakage (the OS will still think you are using the memory since you never released it).
/nebulus
-
Also, remember in C++ you can have protected (private) data, that can't be "touched" by outside functions. I suppose this is more important when you're working with a group of others and you don't want someone else accidentally messing with your data, but it can also help you when you're working on something alone and you have something important you don't want to change unintentionally.
//Edit!
Um, that's protected/private data in your class... should have slipped that in there somewhere...