Sign in to follow this  

Need Help Understanding Classes

This topic is 4596 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi everyone, im still relatively new to c++ programming and programming in general, and was hoping for some help. I've looked at a bunch of examples of user written classes and still kind of confused about it. Since im pretty big with gaming i figure if someone has a gaming example of a class could you show me :). Any help would be appreciated.

Share this post


Link to post
Share on other sites
What exactly are you confused about? Use? Syntax? Properties?

A class represents a concept. It has members that help you implement that concept. Here's an example : a tank from an RTS game (no guarantee this code will compile):


//This is the class declaration - this would go into your tank.h file
class Tank
{
// The public elements of a tank are all those things that other program components can access
public:
// First we need a constructor and destructor
Tank(const Vector2& location);
~Tank();
// What can tanks do?
void Move();
void Move(const Vector2& where);
void Shoot();

// And some accessor and mutator functions
Vector2 GetLocation() const {return position_;}
void TakeDamage(int damage);

// The private elements of the class provide the means of the classes implementation
// Other classes don't access these members, as they have no need to
private:
// First let's store some information about a specific tank
Vector2 position_;
float speed_;
int ammo_;
int health_;
// Now lets add a helper function that will help with our implementation
Tank& FindClosestTarget();
};

// Now we need to provide definitions for all the functions - these will be in your tank.cpp file

// The constructor
Tank::Tank(const Vector2& position) : position_(position), speed_(1.0f), ammo_(10), health_(10) {}

// The destructor
Tank::~Tank() {}

void Tank::Move(const Vector2& where)
{
location_ += speed_ * Normalise(where - location_);
}

void Tank::Move()
{
Tank& enemyTank = FindNearestTarget();
Move(enemyTank.GetLocation());
}

void Tank::Shoot()
{
// Any ammo left?
if(ammo == 0)
return;

Tank& enemyTank = FindNearestTarget();

// Assume always hits
enemyTank.TakeDamage(1);
--ammo;
}

void Tank::TakeDamage(int damage)
{
health_ -= damage;

// Let's assume there is a global ReportAsDead function that cleans up when a tank dies
// Note also the use of the this parameter - this is a pointer to the specific object in question
if(health_ <= 0)
ReportAsDead(this);
}


Tank& Tank::FindNearestTarget()
{
//Pseudo-code
1. Loop through all tanks, and find nearest
2. Return reference to nearest tank
}

int main()
{
// Create a specific instance of a tank
Tank myTank;

// Do some stuff with it
myTank.Move(1,1);
myTank.Move();
myTank.Shoot();

return 0;
};






This is not the best code in the world, but hopefully will give you some idea of what a class can do. It encapsulates all the functionality that you want the associated concept (the tank) to do, and provides a coherent interface for outsides to access and control.

Hope that helps,
Jim.

Share this post


Link to post
Share on other sites
I'll try explaining without too many abstracts. Say you have a character that can throw a ball. You need variables to store the locations of the player and the ball. You also need variables to store the speed of the ball and the name of the character. You need functions that handle moving the character, throwing the ball, and for making the ball bounce.

Here's the code without classes:


// Global variables for the character
string characterName;
int characterX;
int characterY;

// Global variables for the ball
int ballX;
int ballY;
int ballSpeed;

// Functions for the character
void MoveCharacter() { ... }

void ThrowBall() { ... }

// Functions for the ball
void BounceBall() { ... }



There's a lot of problems with this code. We'll just focus on the problem I think you should be worrying about right now though. This problem is lack of organization. You'll soon learn that possibly the biggest part of programming is reducing complexity. As program's grow in size, it becomes more and more difficult to keep everything in your head. For example, I work at a company that's program has over 2.5 million lines of code. It would be impossible to work on that if you had to know what every variable means and what every function does.

That's the problem with the above code. You have to know what each variable and function means, and whether it belongs to the character or the ball. Now just imagine if we had hundreds of things in our program. There'd be variables everywhere and we'd have to know what each one does.

Now here's the code with classes:


class Character
{
public:
// Functions
void ThrowBall() {...}
void Move() {...}

private:
// Variables
int x;
int y;
string name;
};

class Ball
{
public:
// Functions
void Bounce() { ... }

private:
// Variables
int x;
int y;
int speed;
};



I'm obviously ignoring a lot of aspects of classes here, but I just want you to think about how this reduces complexity.

Before, if you wanted to deal with a character and a ball, you'd have to go read the global variables and functions and figure out what each one does. Then you'd have to work with those global variables and functions.

But with our information inside a class, we can forget about what's inside the class and just think about what it does. This is important, we can forget about how it works, and only worry about what it does.

Notice how in the classes above, the functions that represent what the character/ball does are public, but the data that handles how they work is private. The public members of a class are called its interface. If we want a character that moves and throws a ball, we put functions that make the ball move and bounce in its interface. Everything else gets hidden.

This all means that once you've written a class, you can forget about how you made it work and just worry about what it does. Here's an example:

// Create a character, make it move, then make it throw a ball
Character marv;
marv.Move();
marv.ThrowBall();

The character is created, it moves, it throws a ball. All we had to do was say "make a character, move it, throw a ball". We didn't have to worry about how the character does it.

The thing to get out of this is that if you have a concept you need to represent (this can be a character, a car, a bank account...), put it in a class. Once it's in a class and the class works, you can forget about how it works.

I hope I've helped, by all means ask more questions.

Share this post


Link to post
Share on other sites
thanks was very helpful so that's how a large group of programmer's working on a project avoid disaster. If i understood correctly classes allow people to write their own little segments of code without having to worry about someone manipulating how their class works using the private and public features. Now that I look at it its a pretty interesting feature.

Share this post


Link to post
Share on other sites
Yeah, it's amazing that people have written large programs without classes.

Another benefit is that you can reuse the same code easily. I'm writing a new series of game tutorials for my website right now. In each game, there's a ton of classes that are the exact same (character classes, projectile classes, game state classes,...). Instead of rewriting them, I just copy the files that contain them into my new projects. It saves me days of coding.

Share this post


Link to post
Share on other sites
agreed. it also helps you identify easier with what you're using or working with. rather than look at it as a series of crazy variables or pieces of a dynamic array or list, you can just link together things that actually sound tangible.
once you learn how to properly use classes you wonder strongly how or why you ever programmed any other way.

Share this post


Link to post
Share on other sites
Here's what I would say about classes.

You set up a class to encapsulate certain functions and variables within one object, or "class".

Here's a class declaration:


Class Dog
{
public:

void woof();

void SetAge();

void ShowAge();

void walkaway();

private:

int age;

}Fido; // Instance of Dog class "Fido" is created.

//Alternatively, we could put Dog Fido; somewhere - that's the same thing, it creates the instance of the class







We've created a class called Dog, which contains a public member function woof();, SetAge(); and walkaway();, and the int age; is private, meaning only its own member function can alter it.

Here's how we implement the functions:

void Dog::woof()
{

std::cout<<"Woof!\n";

}

void Dog::SetAge()
{

int dogage;

std::cout<<"How old is the dog?";

std::cin>>dogage;

age=dogage;

}

voidDog::ShowAge()
{

std::cout<<"The dog is "<<age<<" years old.\n;

}

void Dog::walkaway()
{

std::cout<<"Dog is walking away...";

}








And here's how we call them. The }Fido; in the class declaration means we already have an instance of the Dog class created, so we can use it immediately.


// We already have the classes declared, they should go at the top of your code or in a header file... I won't retype them here.

int main(int argc, char *argv[])
{

Fido.woof();

Fido.SetAge();

Fido.ShowAge();

Fido.walkaway();

return 0;

}







As you can see in some of the other examples people have given you, some people declare their class member functions like this:


Class Dog
{

public:
// ...
void ShowAge { std::cout<<"The dog is "<<age<<" years old."; }

};





It doesn't matter how you do it, actually the above method is cleaner and clearer imho, but do it how it suits you.

Classes are an integral part of Object Oriented Programming, they're really useful when your projects get larger.

I really hope I've helped you, please ask again if you're stuck.

ukdeveloper.

Share this post


Link to post
Share on other sites

This topic is 4596 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this