#### Archived

This topic is now archived and is closed to further replies.

# Functions and Classes :(

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

## Recommended Posts

First i do no how to define classes. I have never really used them because I dont know HOW to use them. I need some help with wherre I would use them and how to. Second what would i use a class for and how DO i use a class Please help! Ishamael02 Betrayer of Hope Eldar_mage Peter B

##### Share on other sites
A class is essentially a user defined data type (with associated operations). Use it when you need a data type that is not built into the language (say, student or snake as opposed to int or float).

(Yes, there is more to classes - inheritance does spring to mind - but I''m attempting to simplify.)

##### Share on other sites
I havent had to use them yet. But I could see how they could be usefull in the future. Im assumming their like records in Pascal. If im correct then all it is something that stores a bunch of variables.

Lets say you have a class called "person". Under person you could have the variables Age, Job, Sex and other things like that.

Now that you have the datatype Person, you could create a variable of that datatype. Such as Fred and declare him as a "person" datatype.

Now Fred has all these variables built in. You could acces them like so

Fred.Age = 21;
Fred.Job = "Burger Flipper";
Fred.Sex = "Male";

Thats the understanding I have of them. Of course, Im not too sure, Im still learning myself. I also know theres different levels they could go on like "public" and so on. But I dont know how that works.

##### Share on other sites
sum1, what you are describing is a C struct. C++ classes are far more powerful because they also allow you to define the operations you can perform on them (and overload operators to handle these operations). For instance, if you define a class to describe a vector in space, you can also define operations for addition, subtraction, scalar multiplication, dot product, and so on. Furthermore, C++ classes support (and encourage) data encapsulation through the use of access modifiers (private, protected, public), and (very important!) inheritance (which enables you to make use of inheritance-based polymorphism, which is a very wonderful thing to have).

Note that I call them "C structs" and "C++ structs", respectively. You can still have structs in C++, but they are not quite the same thing as in C: In fact, they are the exact same thing as classes, save that they default to public access and public inheritance (as opposed to private in both cases for classes declared with the class keyword, I think). (Personally, I use structs in C++ only when they are C-type structs, but that''s a matter of personal preference.)

##### Share on other sites
By chance I saw this thread, and decided to summerize and add to what has been previously stated. As stated above, classes are a way of defining new (and possibly complicated) data types. Since you know how to define classes, I will assume you know about the difference in private and public members, and that both data and methods(or functions or procedures) may be members.

The first step after defining a class is to instaciate (declare) an object(variable) of the class. This is done just like any other variable declaration. As with the previous examples, if you wanted to declare fred as an object of the class person it would look like this:

person fred;

Optionally, if you have a non-default constructor(that is one that takes parameters) you can instantiate the object like this:

person fred("fred", age); //Example using a non-default constructor

Just in case you don''t know what I mean by constructor, that would be the the member method that is named the same as the class:

class person
{
person(); //default constructor
person(string name, int age); //constructor that takes parameters
};

Now you can use the dot ''.'' to access the members of the object:

fred.age = 18;

The above example assumes that age and name are public members. If they were private you would need to make member functions that access them(which is what I suggest).

Well, there it is, the basics of using classes. I know it is a bit involved, but I hope it helps. If I missed anything of importance, please say so.

##### Share on other sites
anyone out there who has any experiance will now think i am a moron. I have a calcuator I am working on. Boring I know, and it would pobl take you a secod to wip someting up a lot better than this. I want to use classes or funtins to clean this up a bit that is why I asked So I will post the code and ask, with classes and functions how to clean this up! Appreciate the help

//start code
#include <iostream.h>
#include <stdlib.h> //for for system("pause" function
int main()
{
float one, two, three;
char k;
cout << "Welcome To Peter Bretton''s First C++ Program The Calculator!\nIf you find and bugs please notify me immediatly\nCalculator v1.0"< cout << "What kind of problem do you wish to do (m)ultiplycation/(a)ddition/(d)ivision/\n(s)ubtraction): ";
cin >> k;
if (k == ''m'')
{
cout << "Please enter a number to be multiplyed: ";
cin >> one;
cin >> two;
three = one * two;
cout << one << " times " << two << " = " << three << endl;
system("pause");
return 0;
}
if (k == ''a'')
{
cin >> one;
cin >> two;
three = one + two;
cout << one << " times " << two << " = " << three << endl;
system("pause");
return 0;
}
if (k == ''d'')
{
cout << "Please enter a number to be divided: ";
cin >> one;
cin >> two;
three = one / two;
cout << one << " divided " << two << " = " << three << endl;
system("pause");
return 0;
}
if (k == ''s'')
{
cout << "Please enter a number to be subtracted: ";
cin >> one;
cin >> two;
three = one - two;
cout << one << " minus " << two << " = " << three << endl;
system("pause");
return 0;
}
}

Help!

Ishamael02
Betrayer of Hope
Eldar_mage
Peter B

##### Share on other sites
P.S.

It does work how I want it to but the code is not pretty.

##### Share on other sites
P.S.

It does work how I want it to but the code is not pretty.

Ishamael02
Betrayer of Hope
Eldar_mage
Peter B

##### Share on other sites
Try this. This uses functions to make your calculator:

  #include<iostream>#include<stdlib.h>int Add(float x, float y, float z){	z = x + y;	std::cout << x << " + " << y << " = " << z << std::endl;	return 0;};int Subtract(float x, float y, float z){	z = x - y;	std::cout << x << " - " << y << " = " << z << std::endl;	return 0;};int Mult(float x, float y, float z){	z = x * y;	std::cout << x << " * " << y << " = " << z << std::endl;	return 0;};int Div(float x, float y, float z){	z = (x / y);	std::cout << x << " / " <<  y << " = " << z << std::endl;	return 0;};int main(){	main:		float x, y, z;        char function;	std::cout << "Calculator!" << std::endl;     while (function != 0)    {    std:: cout << "Enter a function, and then two numbers! (Enter 0 for function to exit!)" << std::endl;	std::cin >> function;    if (function == '0')       return 0;    std::cin >> x >> y;	switch(function)	{		case '+':Add(x,y,z); 			 break;		case '-':Subtract(x,y,z);			 break;		case '*':Mult(x,y,z);			 break;		case '/':Div(x,y,z);			 break;		default: std::cout <<"Invalid function!  Please try again!" << std::endl;			 goto main;	}    };		system("PAUSE");	return 0;}

~del

[edited by - Del Snd of Thndr on November 20, 2002 11:36:03 AM]

##### Share on other sites
The include statements use iostream and stdlib.h. Also, for sake of neatness, you can drop the "main:" and "goto main;" statments. However, if you do this, you might want to replace "goto main;" with "break;"

~del

##### Share on other sites
Well for starters you don''t need to go all out with classes and such with your calc program. You need to learn how to use functions first. Good use of functions would make your code about 1/4 the size it is now, and it would do the same thing...probably more efficiently.

But anyway, if you want to do any kind of real game programming, classes are a must. I use classes extensively to build game engine components. For instance, say for a particular engine you have these components:

- Graphics
- Sound
- Input
- Physics
- AI

You could create a class for each component. Each component also could have sub components:

- Graphics
- points
- lines
- rectangles
- circles

You get the idea. Classes let you create these objects such that they contain all the properties that the class defines (member functions/vars). For example...

Say I have a class named ''point''. In my point class I want to have the member variables for the point''s location:

private:
int x, y, z;

and some functions to set the point''s coords:

public:
set_x(int x1){x = x1;}
set_y(int y1){y = y1;}
set_z(int z1){z = z1;}

// and retrieve the point''s coords
x(){return x};
y(){return y);
z(){return z};

and maybe a function to display the point on the screen:

(public
display_point(int x, int y, int z, char color);

now in my client program, point manipulation becomes easy. Rather than have to write every single line of code to put a point on the screen at , you simply use your class like a toolkit:

point p1;
char color = 255;

p1.set_x(0);
p1.set_y(0);
p1.set_z(0);

// display a white point on the screen at 0,0,0
p1.display_point(p1.x(), p1.y(), p1.z(), color);

Now obviously I left a lot out (constructors, destructors, protected, etc...), but I was simply trying to demonstrate the usefulness of classes.

Hope this helps to get you pointed in the right direction as far as classes go.

-Q

"You no mess with Lo Wang!"
-Lo Wang (SW)

##### Share on other sites
Again, the #include statments use iostream and stdlib.h. Using classes:

  #include<iostream>#include<stdlib.h>class Calc{   public:   void SetFunction(char);   void SetInputs(float, float);   void Add();   void Subtract();   void Mult();   void Div();   void PrintResult();   private:   char function;   float input1, input2, result;};void Calc::SetFunction(char z){   function = z;};void Calc::SetInputs(float x, float y){   input1 = x;   input2 = y;};void Calc::Add(){   result = input1 + input2;};void Calc::Subtract(){   result = input1 - input2;};void Calc::Mult(){  result = input1 * input2;};void Calc::Div(){  result = (input1 / input2);};void Calc::PrintResult(){   std::cout << "Result = " << result << std::endl;};int main(){   Calc calculator;   float x, y;   char z;   std::cout << "Calculator!" << std::endl;   main:   std::cout << "Please enter a function and then two numbers!  Enter 0 to finish!" << std::endl;   cin >> z;   while(z != '0')   {      calculator.SetFunction(z);      std::cin >> x >> y;      calculator.SetInputs(x,y);      switch(z)      {         case '+':calculator.Add();                  break;         case '-':calculator.Subtract();                  break;         case '*':calculator.Mult();                  break;         case '/':calculator.Div();                  break;        default:  std::cout << "Invalid function!  Please try again!" << std::endl;                  goto main;       };       calculator.PrintResult();       std::cout << "Please enter a function and then two numbers!  Enter 0 to finish!" << std::endl;       cin >> z;    };       system("PAUSE");       return 0;}

Not the prettiest code, but it works.

~del

[edited by - Del Snd of Thndr on November 20, 2002 11:35:02 AM]

##### Share on other sites
quote:
Original post by Ishamael02
First i do no how to define classes. I have never really used them because I dont know HOW to use them. I need some help with wherre I would use them and how to.

I guess defining a class in itself is quite simple, but there are quite a lot of pitfalls to be aware of. Fortunately, you can probably ignore a few pitfalls to begin with. In thinking about objects and classes, you need to recognise that classes have data to identify their state, just like C-style structs, and they also have behaviour, which can be represented by member functions of the class. This is an inversion of what you''d do in C, where you''d have a number of freestanding functions which can act on particular structs - instead you consider those freestanding functions for membership within the class. A good heuristic here is do they need direct access to the data which makes up the class? If they do, then they should probably go in the class.

Before you decide to create a class, you need to have identified a need for one. It can be tricky to know when to use a class and exactly what should go in it, but you should get better as you gain experience. A simple rule for finding when you have a candidate for a class is to think about the program you are writing and what objects are going to exist in that program. If you were writing Breakout, you could come up with some obvious objects straight away: the bat, the ball, bricks, bonuses, etc. There might also be some not-so-obvious objects, such as a joystick or keyboard, the screen, etc. You don''t need to identify *all* objects at first, just find some so that you can start to think about your gaming world. How do these objects relate to one another? What are the commonalities and the differences between them? You might say that all bricks are obviously the same type of thing, so they can all be represented by one class. OTOH, bat and ball objects have different behaviour to bricks - they can move around the screen - so they clearly aren''t the same type of thing as a brick.
quote:

Second what would i use a class for and how DO i use a class

This is a tricky one, because there''s quite a lot to be said about classes. To avoid doing yourself an injustice, you really need to get yourself a good book. Are you using one at the moment? If you have some programming experience, Accelerated C++ might be a good bet. I''ve tried to answer some of this above, but I can''t do the subject justice in a short post.

##### Share on other sites
quote:
Original post by Ishamael02
anyone out there who has any experiance will now think i am a moron. I have a calcuator I am working on.

IIRC, there is a calculator example in Stroustrup''s The C++ Programming Language.

##### Share on other sites
Thanks a lot for the help:
(Wish I understood little more sigh )
Oh well. Im reading up on it from a tut now anyways. It really helped

Ishamael02
Betrayer of Hope
Eldar_mage
Peter B

##### Share on other sites
Teach Yourself C++ in 21 Days is online (albeit, it''s only the 2nd edition) at: http://newdata.box.sk/bx/c/ It''s a pretty good book. It''s what I used to learn C++. I''m by no means a pro, but the author has taught me how to use functions, classes, etc. You might want to check it out.

~del

##### Share on other sites
ok. I give up I read the class tutorial and I still couldn''t get it to work

#include
#include <stdlib.h>
class person
{
public:
person(); //default constructor
person fred("fred", int age); //constructor that takes parameters
};

int main()
{
fred.age=30;
cout << "Fred is "< system("pause");
return 0;
}

after I copile this I get a two of error messgages.

7 C:\Documents and Settings\All Users\Documents\classes.cpp
parse error before )''

and

13 C:\Documents and Settings\All Users\Documents\classes.cpp
fred'' undeclared (first use this function)

I AM CONFUSED!

##### Share on other sites
quote:
Original post by Ishamael02
I AM CONFUSED!

Yes, you are.

      #include <iostream>#include <stdlib.h>#include <string>using namespace std;class person{// Where is this 'age' you refer to? And where is the name?private:  int age;  string name;public:  person(void); //default constructor - needs a body somewhere!  person(string inName, int inAge); // One that -takes- parameters/*This makes no sense. The constructor must have a name, and the first parameter cannot be a constant. If you want to create a person called 'fred', you will -call- the constructor with the string "fred" as the first parameter.*/  //person fred("fred", int age); //constructor that takes parameters  // We'll also need an accessor for the age  int GetAge(void) { return age; }};// We need method bodies!person::person(void){  name = "Unnamed";  age = 0;}person::person(string inName, int inAge){  name = inName;  age = inAge;}int main(void){  // Must declare and initialise object first! Like so:  person fred("fred", 30);  // No need to set the age; this is what constructors are for  //fred.age=30;  // If age is private, you'll need an accessor function  cout << "Fred is " << fred.GetAge() <<" years old" << endl;  system("pause");  return 0;}

[edited by - Miserable on November 19, 2002 6:35:12 PM]

##### Share on other sites
How do you post code like that??

~del

##### Share on other sites
Yeah...how DO you post code like that???

-Q

##### Share on other sites

  #include<iostream>      /*headers*/#include <stdlib.h>using namespace std;   /*makes sure I don''t have to write "std::" in front of every "cin" and "cout"*/class person  /*this is defining a class called "person"*/{public:          /*anything under "public" in a class definition can be accessed or changed by anything in the program*/person(); /*default constructor, does nothing but set aside memory for a "person" object*/                     /*these constructors make a "person" object*/person (int); /*constructor that takes parameters*//*having two constructors means you are OVERLOADING the constructor, this means that you can set it up to where a person can pass all kinds of values to the constructor (setting up the object)*/~person();/*default deconstructor...destroys the object when the program is finished with it*/void SetAge(int);  /*this is a function that will set age...notice it is passed an integer*/void PrintAge();   /*this is a function that will print the age to the screen*/private:   /*anything under "private" in a class definition can only be accessed by that classes member functions (the functions under "public")*/int age;  /*this is the age of the "person"*/};          /*this is the end of the "person" definition*/person::person() /*this is the default constructor...it does nothing except create the person*/{};person::person(int x)  /*this is the other constructor....if passed a value, it will set age to be equal to the value passed*/{   age = x;};         /*this is the end of the person(int) constructor definition*/person::~person()  /*this is the default deconstructor...it destroys the object when it is no longer needed*/{};void person::SetAge(int x)   /*this is a function to set the age of a "person"*/{   age = x;  /*sets the age*/};                           /*end of function SetAge*/void person::PrintAge()      /*this is a function that outputs the age of a person to the screen*/{   cout << "The person is " << age << " years old.\n"; /*notice I used "age" and not "fred.age"*/};                          /*end of function PrintAge*/int main(){person fred;    /* this makes an object called fred.  the object is of class type person.  fred takes all attributes of a "person."  also notice there are no parameters                   this means that fred will go to the default constructor (the one that has no parameters passed into it)  if you wanted to set the age in the declaration here,                   you would put:  person fred(35)   where 35 is the age.  since this statement has a parameter (or argument), it would go to the constructor                   with matching parameters*//*Now you want to set the age of "fred"*/int x;  /*an integer that the person will supply as the age of the person created*/cout << "Input an age!\n";cin >> x;fred.SetAge(x);  /*this tells the compiler to run the SetAge function for "fred"*/fred.PrintAge();  /*this tells the compiler to run the PrintAge function for "fred"*//*notice I put the object name, then a period, then the name of the function to callwithing the class definition...it will run that function for that object only...that way, you can keep up with a lot of objects with different values at once*/system("PAUSE");  /*pauses the console*/return 0;   /*this returns a zero value to the system and exits the program*/}/*This program will compile and run for you.  If you want, put some cout statments in thedefault constructor and destructor see when they are called, etc.  Just mess around, screwing itup and fixing it again.  Also, you may want to check out "Teach Yourself C++ in 21 Days."The second edition is posted on the web.  Just go to Google, type in "teach yourself c++ in 21days" and hit "I''m Feeling Lucky!" and it will take you there.  If you have any additional questionsyou can email me at delsnd@delsndofthndr.com.Good luck!*/

p.s. put (source)(/source)...replacing the parentheses with brackets

~del

##### Share on other sites
Oh yeah...



just had to quote someone. lol

-Q

##### Share on other sites
Oh yeah...



just had to quote someone. lol

-Q

##### Share on other sites
On a side note (to Qa303asmGuru and Del Snd of Thndr), you can delete (redundant) posts by editing them (check the box and make the modifications). No need to inflate the thread with large, empty source boxes, even though I do understand why you''d want to experiment.

(Heh, I''m starting to act like an overzealous moderator. I suppose my IRC chanop days left a lasting impression ...)

##### Share on other sites
Heh, sorry about that double post...I wasn''t sure if the original posted b/c I didn''t realize it went on page 2!!!

Doh!

-Q

• ### Forum Statistics

• Total Topics
628735
• Total Posts
2984449

• 25
• 11
• 10
• 16
• 14