Friday, July 31, 2009

I dont understand C++ Classes, explain please?

I am having trouble grasping C++ classes I have read about 4 tutorials but im still confused, can someone give me a plain and simple guide of what they are how to use them please, im really annoyed at not being able to understand them.

I dont understand C++ Classes, explain please?
a class is the definition of a box of variables, so if your program acted upon cats, you'd make a class called cat.





class cat


{


char[15] color,


int numberOfWhiskers;


};





so what can you do with that? (well, nothing but define cats)





cat Sam,


Hal,


Morty;





now there are three cats (but in classes all the members are private unless declared otherwise, so you need functions (or to declare members as public)!





so Hal.numberOfWhiskers will give an error.





so we change the class to





class cat


{


char[15] color,


int numberOfWhiskers;


public :


void addWhisker();


void cutWhisker();


}





now you can give the cat whiskers or cut them off!


say you have the code (and pretend with me that a class will by default assign 0 to its members, which it won't):








void cat::addWhisker()


{


whisker++;


}





bool cat::cutWhisker()


{


if (whiskers %26lt;=0)


{


whiskers = 0


return false; //nothing changed


}


else


{whiskers--;}





}





In this way we can ensure that if a member variable needs to be created specially, then it is, you can't have a negative amount of whiskers.





There is also a function that you define:





cat::cat





that is run whenever the class is instantiated, that is everytime there's a statement like


cat Tim;


cat::cat will run on the cat tim.


This function SHOULD set every member variable, unless you have a good reason not to. it can even have arguments making it





cat Tim(7);





if you define it that way.





there's also a destructor, but it's usually only used for dynamic memory.
Reply:To understand what classes are, you should research Object Oriented Programming. See the Wikipedia link attached for some basic information.
Reply:First off, take a deep breath and be a little easier on yourself. Many people have problems grasping classes and even more think they understand them better than they really do. It takes time and effort but when the light bulb goes on you will be grateful you made the effort.





There is no way anyone here can explain classes in a limit amount of time and space. Re-read your tutorial or find better ones. There are literally hundreds available for free on the web.





One way to approach the problem is to try and put into sentences what it is you think you don't understand. That alone may help. And smaller questions are easier for people here to answer.


No comments:

Post a Comment