C and C++ Programming Resources

Custom Search

Introduction to Classes in C++

The data types we have applied so far to our variables were used to identify individual items. To create more advanced and complete objects, C++ allows you to group these identifiers and create a newly defined object.

An object, such as a CD Player, a printer, a car, etc, is built from assembling various parts. In the same way, C++ allows you to group various variables and create a new object called a class.

What is a Class?

A class is an orgnisation of data and functions which operate on them. Data structures are called data members and the functions are called member functions, The combination of data members and member functions constitute a data object or simply an object.

Imagine a company that manufactures shoe boxes hires you to write a program that would help design and identify those shoe boxes. A shoe box is recognized for its dimensions (length, width, height), color, and shoe size that a particular box can contain, etc. The variables that characterize such an object could be:

double Length, Width, Height;
char Color;
float ShoeSize;

A Class Example

class ShoeBox
{
  double Length, Width, Height;
  char Color[12];
  float ShoeSize;
};The items that compose a class are called members of the class.

And the program that defines a shoe box object could be:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
	// Define the characteristics of a shoe box
	// The following characteristics are COMPLETELY random
	double Length(12.55), Width(6.32), Height(8.74);
	string Color("Yellow Stone");
	float ShoeSize = 10.50;

	// Display the characteristics of the shoe box
	cout << "Characteristics of this shoe box";
	cout << setiosflags(ios::fixed) << setprecision(2);
	cout << "\n\tLength = " << Length << "\n\tWidth = " << Width
	<< "\n\tHeight = " << Height << "\n\tVolume = " << Length * Width * Height
	<< "\n\tColor = " << Color << "\n\tSize = " << ShoeSize << "\n\n";

	return 0;
}

The program would produce:
Characteristics of this shoe box

Length = 12.55
Width = 6.32
Height = 8.74
Volume = 693.22
Color = Yellow Stone
Size = 10.50
Press any key to continue...

Unless dealing with one shoe box, this program would be rudimentary to run for each object. The solution is to create an object called box that groups everything that characterizes the object.

Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4] [Page - 5] [Page - 6] [Page - 7] [Page - 8]

Tags: , , , , ,

There are 16 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.


Leave a Reply

You must be logged in to post a comment.