Classes and their uses

Hello. I'm a new programmer, and have been going through the tutorial on this site. It's easy enough to understand, but it doesn't do a very good job about showing when and how to use the topics it explains. For example, it goes through a whole huge tutorial about how to use classes to determine the area of a square. The following code is directly from the tutorial.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// classes example
#include <iostream>
using namespace std;

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

int main () {
  CRectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}



They go on to explain constructors and destructors, which I mostly understand. What confuses me is why that is more efficient than simply using variables. That would allow for more than one area to be entered and would use less code and time. It would probably also cut down on the executable's size and run time. For example, I would have written the following code instead.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int side, area, yesno; //global side and area vars

int get_area(int side) { //function to calculate the area from the side
     area=side*side;
}

int main() {
cout<<"Area Finder \n";
do {
cout<<"Do you want to find another area?  Enter 1 for yes, and anything else for no.  /n";
cin>>yesno;
cout<<"Enter the length of a side of the square and press enter.  \n";
cin>>side;
cout<<"The total area of the square is "<<get_area(side)<<"\n";
cout<<"Do you want to find another area?  \n";
cin>>yesno;
}
(while yesno==1);

return(0);
}


I did this without a compiler so there may be a few syntax-related or technical errors, but you get the idea.

Can someone explain to me what the best time to use classes is? They'd be great if you could define objects of them in the main body, with computer-generated names, like as in the user creates a new object each time they ask to generate another area.

Thanks,
-Ameobea
You can use classes as variables in a loop, just like you use variables. One of the most important ideas about classes is data hiding. When you get further along, you will discover how essential it is that classes hide the details of the object and also give you an interface into the object without using global variables. For example, you might write a library of code that works on different shapes and different types of variables for calculating the areas of different shapes. One day, for example, you find a better way of coding your classes. If you don't change the interface into your objects, you can just ship the latest binaries of your library and all the programmer who is using your library needs to do is to relink their code.

I hope that gets you curious!
Yes, it did. What exactly is data hiding? I googled it and read an article on another site about it, but it was very strange and full of veteran programmers complaining about messy workarounds and whatever.

I don't understand why you'd need to keep data private form the rest of your code. The only reason I could think of for that would be overloaded functions, where people think it's easier to name functions the same thing.

Can you clarify that for me?
-Ameobea
Quoting from "Thinking in C++" by Bruce Eckel:

There are two reasons for controlling access to members (data hiding). The first is to keep user's hands off tools they shouldn't touch, tools that are necessary for the internal machinations of the data type, but not part of the interface that users need to solve their particular problems. This is actually a service to users because they can easily see what's important to them and what they can ignore.

The second reason for access control is to allow the library designer to change the internal workings of the structure without worrying about how it will affect the client programmer.


You really should check out this book!
in short codes we cant see the advantages of class compared to just calling function. but if you have hundreds of object within loop we will see. if we have huge of student with every point in examp may be can be used like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;
class student
	{
		public:
		char name[50];
		int number,point1,point2;
		
		student(){}
		int sum()
		{
			return point1+point2;
		}
		void display()
		{
			cout<<"\n\n\n-----------------";
			cout<<"\n"<<number<<" "<<name;
			cout<<"("<<point1<<","<<point2<<") sum : "<<sum();			
		}
		
	};
int main(int argc, char *argv[])
{
	int answer;
	int counter;
	string str_answer;
	student *yourstudent;
	cout<<"\nhow many student do you like to add : ";
	cin>>counter;
	yourstudent = new student[counter];
	for(int i=0;i<counter;i++)
		{
			yourstudent[i].number=i;
			cout<<"\n------------------------------";
			cout<<"\nFOR STUDEN NO. "<<i;
			cout<<"\nName : ";cin>>yourstudent[i].name;			
			cout<<"\nPoint 1 : ";cin>>yourstudent[i].point1;
			cout<<"\nPoint 2 : ";cin>>yourstudent[i].point2;
			system("cls");
		}
	for(int i=0;i<counter;i++)
		{
			yourstudent[i].display();
		}
		
	do
	{
		system("cls");
		cout<<"which number of student do you like to see ? :";
		cin>>answer;
		if(answer >= 0 && answer < counter)
			{
				yourstudent[answer].display();
			}
		cout<<"\nwanna see more student ?(y/n) ";
		cin>>str_answer;
	}while(str_answer != "n");
	delete[] yourstudent;
	
	cout<<"\n\n";
    system("PAUSE");
    return EXIT_SUCCESS;
}


in the main program you dont have to know how the student.display work. you just call student.display and what to display, it's just a small function , you may think to more complext fucntion with many value to pass , with just reguler function we need to write every value to fit the function needs.

 
display(number,name,point1,point2)


its gonna be no froblem if it just 4 argument to write, but if it 50 or more its will be interest you just to write verry long codes.

with class we only need to know which object to handle, and everything is done within object itself without our attention. with class we able to make thousand object and every object work itself just like how the class defined. sorry for my bad english
Hi,

A class is a userdefined type.
you creates a new kind of property which includes a lot of you know.

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class x{
int i;
public:  
	x(int ii) // constructor
	{ 
		i = ii; 
		cout << "I am constructor\n" << endl; 

	}
	~x()
	{
		cout << "I am destructor\n" << endl; 
	}
};
Thanks for all the help! This makes a lot of sense. However, I still have just one more question. From that quote from that book, it said that it would
"... keep user's hands off tools they shouldn't touch, tools that are necessary for the internal machinations of the data type."

I don't understand how someone could get into those functions, as they're totally restricted to the code. How could someone access those from a console or window?

-Ameobea
What he's talking about there is that in C, strutures and variables are accessible to a programmer. With classes, it is harder to get to the private and protected object items (without hacking.) One should think of objects in terms of their interface (i.e.: How you use the object.)
In a binary .exe, it is impossible to edit them without a hex editor or disassembler/assembler to edit the assembly code. You're talking about if you give another programmer a c++ source file instead of a binary, right?

I'm really isolated as to sharing anything with anyone except on these forums, and am not woking on anything private or anything. Anyway, you couldn't access any of those functions directly through a console or window, right?
Right.
Thanks, all, for your help!
object usually has a properties and methods, we can say function within class as method and variable as properties, but properties are read-write and read only, to make read only properties we use private and read it with function within the class it self , why we need readonly properties ? i cant tell in english but with this code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class ticket
{
	private:
		static int counter;
		int number;
	public:
		int ticketnumber()
			{
				return number;
			}
		int sold()
			{
				return counter;
			}
	ticket()
		{
			counter++;
			number=counter;
			
		}
};

int ticket::counter = 0;

int main(int argc, char *argv[])
{
	cout<<"Hello C-Free!"<<endl;
	ticket boys[5];
	ticket girls[3];
	cout<<"\nTicked number on Gilrs no. 2 is "<<girls[2-1].ticketnumber();
	cout<<"\nTicket number on boys no. 3 is "<<boys[3-1].ticketnumber();
	cout<<"\n\nSold Ticket : "<<boys[0].sold();
	
	cout<<"\n\n\n";
	system("pause");
	return 0;
}


we cant access counter or number from main program nor function, but we can read them from member function
1
2
3
4
5
6
7
8
                int ticketnumber()
			{
				return number;
			}
		int sold()
			{
				return counter;
			}

in this case we have no access to write into number or counter but its created automatically when object created. with static counter we get different number for every object, we isolate this counter to make another object flows without programmer intervention.

tell me if i wrong about this
in thousand line of codes we forget which one to read or to write, with private previlage its invisible to programmer,
closed account (3pj6b7Xj)
I use classes myself to represent objects, that is the way I learned. In my mock up of Nibbles game, the Snake itself is a class with many variables and functions. I can however, create a function or declare some variables that handle a snake but if I want two snakes, then I have to re-write a load of code for another one and after a while it looks very messy and nasty.

Look at this example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
    int rectangle_x = 10;
    int rectangle_y = 10;
    int rectangle_width = 100;
    int rectangle_height = 100;

    // make another
    int rectangle_2_x = 10;
    int rectangle_2_y = 10;
    int rectangle_2_width = 100;
    int rectangle_2_height = 100;

    return 0;
}


I could of done this instead...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <vector>

using std::vector;

class rectangle
{
     public:
     rectangle() { x = 10; y = 10; width = 100; height = 100; }
     void setwidth(int newidth) { width = newidth; }
     void setheight(int newheight) { height = newheight; }
     void setxy(int newx, int newy) { x = newx; y = newy; }
     int getx() { return x; }
     int gety() { return y; }
     int getheight() { return height; }
     int getwidth() { return width; }

     protected:
     int x,y;
     int width;
     int height;
};

int main()
{
     rectangle myrectangle;
     myrectangle.setxy(10,10);
     myrectangle.setwidth(100);
     myrectangle.setheight(100);

     vector<rectangle> myrectangle(6);

     myrectangle[3].setxy(10,10);
     myrectangle[3].setwidth(100);
     myrectangle[3].setheight(100);

     return 0;
}


there is so much you can do with classes, the whole idea is that anything you make with a class, is an object and that object behaves in the manner you want it too and takes care of anything related to it, the rectangle may have a maximum width or height, it may even detect if its out of the screen or not...doing it out of a class would require to write the same code over and over again.

I threw a vector in there just to show an example.

By the way, I am also new here, and not sure if I contributed to this properly so forgive me I have not.
Last edited on
Thanks again! You're all a great help.
Topic archived. No new replies allowed.