Originally Posted by
Smeep
Lol, 7stud, you'll appreciate this more than anyone else here, but that's what I'm doing with my Orc at the moment.
Attempting to make a class (monster) So that I could just use it to define Orc. Have some troubles geting the variables to pass about properly, (IE - Something that should be returning 11, is returning 0?)
But that's another story.
Class's confuse me, but I will succeed!
As a first pass, just think of classes as fancy arrays. Like an array, a class is just a container with data inside it. However, instead of accessing the data with an integer index as you do with an array:
myarr[0]
you access the data with a name:
myobj.color
which makes it much easier to know what the data is. After all, how descriptive is myarr[0]? So, a simple class would look like this:
Code:
class Apple
{
public:
string color;
int size;
};
The useful thing about that class is that unlike an array, it can store different types inside it. With an array, you can only have all int's, all doubles, etc. inside it. With a class, you can have all different types inside, and you just access them by name:
Code:
#include <iostream>
#include <string>
using namespace std;
class Apple
{
public:
string color;
int size;
};
int main()
{
Apple MyApple; //create your 'array substitute'
//assign the members some values:
MyApple.color = "red";
MyApple.size = 5;
//output the values:
cout<<MyApple.color<<endl
cout<<MyApple.size<<endl;
return 0;
}
One of the most interesting 'types' a class can contain inside it is a function. It's almost just like calling a regular function--except you precede the function call with the name of the container:
MyApple.displaymembers();
A function inside a class can also operate directly on the other members of the class. For instance, this is what adding a displaymembers() function to the Apple class would look like:
Code:
class Apple
{
public:
string color;
int size;
void displaymembers()
{
cout<<color<<endl
cout<<size<<endl;
}
};
The displaymembers() function can 'see' all the other class members. Here is an example of how you would use that class function:
Code:
int main()
{
Apple MyApple; //create your 'array substitute'
//assign the members some values:
MyApple.color = "red";
MyApple.size = 5;
//call Apple function:
MyApple.displaymembers();
return 0;
}