Monday, May 24, 2010

Can you please explain to me how to make a C++ class?

I have looked everywhere for the tutorials, but none of them explain the answer fully. I think I get a good idea of it, then I run into something I don't unbderstand, so then I look for another tutorial and they explain it in a whole diofferent matter that confuses me. So far, this is what I think a class is





class person


{


int age;


int height;


char *name; (which I have no Idea what a character pointer is for)


char *nationality;


char *gender;


}


occupation; (Would occupation be an object of the person class?





And please explain what constructors and deconstructors are, and what they are used for (I think constructors are used to bring an object to life)


I would prefer if you made a class with a deconstructor and constructor and explain in detail with as simple an explanatiopn as possible.


THANK YOU!!!!!

Can you please explain to me how to make a C++ class?
It appears to me that you are beginning to have the basics down.





A class is a template to be used in creating an object. The class defines properties (variables) and behaviors (methods) that the object will possess.





From your example, occupation is a property of a person, and can be a reference to an occupation object as you mentioned.





You could then go further and define a method called changeOccupation or setOccupation that will allow you to change the occupation of that person object.





This combination of property and behavior define a class.





Constructors:





person::person() {


//do nothing


}





or





person::person(int iAge, int iHeight, ...) {


age = iAge;


height = iHeight;


}





Constructors are special class methods that you use to create the class. These methods can contain code that sets the "initial conditions" of the object when it's created, or allow the user of the class to pass values that will be used to set these initial conditions of the object. For instance you could use the constructor to set the age, height, etc of your person object when you create them.





Destructors:





person::~person() {


cout %26lt;%26lt; "Exiting Person Class Destructor!!!" %26lt;%26lt; "\n";


}





Destructors are called when the object made from the class is being destroyed, and will allow the class to clean up after itself (for instance closing database connections, or cleaning up pointers, etc.)





Check out Bruce Eckel's "Thinking in C++" you can download them for free from his site. I think he does a great job of explaining programming languages so you can understand them... not just the "how" but also the "why".


No comments:

Post a Comment