Advertisement

Classes

Started by July 05, 2001 11:09 AM
3 comments, last by Samurai_x 23 years, 4 months ago
Could someone explain classes and how they are used.
Classes are used for way to many things than can be explained here and even though I am a beginner, I can probobly help somewhat. If you know what a structure is then just imagine a structure with methods (functions). That''s the basic idea anyway.

+||+
+||+
||
||
||
||
||
/||\
{/ || \}
{/ || \}
| || |
\ -- /
\______/
Advertisement
The idea is to represent real-life objects with classes, because you naturally think about objects in terms of their attributes and what they can do. For example, you could write a Car class (about the most used teaching example ) that has data items (called properties, or member data - member because it is a member of a class) such as color, max_speed, engine_size, state (moving/stationary etc) and probably many more. You also package into the class the things that the car can do, ie the functions that operate on the data, these are called member functions or methods. A quick example

In the .h file

#ifndef CAR_H
#define CAR_H

class car
{
public:
// data here
float max_speed;
bool isGoing;

//constructor defintion
Car();

//a member function to set isGoing
void setState(bool state);

//member function to get is going
bool getIsGoing();
};

#endif


Then in the .cpp file

#include "car.h"
// constructor defintion, (it''s empty)
Car::Car()
{
}

void Car::setState(bool state)
{
isGoing = state;
}

bool Car::getIsGoing()
{
return isGoing;
}


If you don''t understand why you need to put the code into a .cpp file - that''s a good thing to find out.

Hope this helps
Thanks I understand a little more now.
I think of classes as a black box. All that you are really concerned about is the interface into that black box. Take for example a microwave. It has a few public things like the timer and door. The rest of the stuff like the internal wiring and stuff you don''t really want to have to know about. This is the private stuff. This is stuff you don''t want anybody playing around with .

You can now have:
  class microwave{   public:      void openDoor();      void closeDoor();      void SetTimer();      bool isDone();   private:      // All the fancy stuff that makes it work};  


Now whenever you want to use the microwave you just have to remember how to use it. You don''t need to figure out how all the wiring works each time . This way its wrapped up in a neat little package.

There are lots more to classes but this should help to get started.

-------
Andrew

This topic is closed to new replies.

Advertisement