View Full Version : can someone explain this c++ code??

02 February 2007, 08:19 PM
can someone explain this c++ code??

and plz indepth

02 February 2007, 08:47 PM
If you wanted this program to be rewritten in two lines, it would look like

void main()
int height = 30, width = 80;
cout<<"Area is "<<height * width;

basically, what the above program does is, it takes width and height of a rectangle, and prints the area. But there is not much you can do with the above program. First of all, it is not generic, ie., I can't give it any rectangle in space and ask it to calculate the area. Second, it is not organized properly - just two variables, which we could even have done without.

This is where object oriented programming comes in. In the program that you had sent, they have encapsulated all the properties of a rectangle into a rectangle class. A class is like a vending machine..where you can put in stuff (data), and even put in functions that can make use of the data (the controls in the machine). The rectangle class stores the coordinates of the rectangle, and also some functions which lets you fill up the values of the coordinates, and also make use of these values by getting them, and getting the area of the rectangle. Such functions also protect the data from us, allowing us to only use the functions to touch the data, so that we don't accidentally change any values.

Each coordinate of a rectangle has an X value, and a Y value. The program would look awful if you went on declaring each one of these seperately. That's why they have defined a seperate class called Point, which is an elegant way of defining a coordinate. Finally, in the main function (which gets executed when you run the program), they have instantiated the class, filled it up with values, and have used it to print the area.

Neat, ain't it?

02 February 2007, 11:44 AM
What was wrong with the explanation below the code?

02 February 2007, 02:43 PM
the problem is that i dont understand how to put a class in a class and how it works

could somebody explain to me how it works and how to write the code right ???

02 February 2007, 03:27 PM
Thinking In C++ by Bruce Eckel ( is freely (and legally) downloadable. I think you want to look at the bits covering inheritance.

02 February 2007, 08:19 AM
the problem is that i dont understand how to put a class in a class and how it works

In the example you provided (Which looks to me like something from a Sams Teach yourself book) there are no nested classes.

You probably meant you don't understand how to instantiate a class, or something. Please be more clear about what you want to know.

I'd actually recommend you get the book that odubtaig mentioned and read it from the beginning.

CGTalk Moderation
02 February 2007, 08:19 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.