Page 1 of 1

C++ BEGINNER BARE BONES CLASS TUTORIAL C++ BEGINNER BARE BONES CLASS TUTORIAL Rate Topic: ****- 2 Votes

#1 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 101
  • View blog
  • Posts: 453
  • Joined: 02-May 09

Posted 06 June 2009 - 12:43 PM

C++ BEGINNER BARE BONES CLASS TUTORIAL

WHAT YOU WILL LEARN IN THIS TUTORIAL

1. You will learn how to declare a class.
2. You will learn how to instantiate a class object.
3. You will learn the basic class vocabulary.
4. You will learn how to define member functions.
5. You will learn how the main() function calls member functions.
6. You will learn how to perform an analysis of a C++ program.

• I. ASSUMPTIONS

Hello; nice to meet you. I assume you are a C++ beginner programmer struggling with learning to use C++ classes, and you have a C++ compiler.

• II. INTRODUCTION

This tutorial discusses the basics of C++ classes.
Using the Pythagorean Theorem “A squared plus B squared equals C squared;” and the Cartesian coordinate system, we will analyze the attached C++ program which computes the distance from the origin to any user inputted point. Our analysis will help you understand the basics of C++ classes.

Copy and paste the following program into a file readable by your C++ compiler. Build, debug and run the attached program. Then follow along with the tutorial, referring back and forth to the program to help you understand how to use C++ classes.

//************************************

#include <iostream>
#include <math.h>
using namespace std;

//************************************

class Point
{

	public:

		Point(float x, float y);					//  1.  Constructor that takes user inputted arguments (x, y).
		float distance(Point p);				//  2.  Distance from origin to user inputted point.
		float x();							//  3.	x-coordinate.
		float y();							//  4.	y-coordinate.
		void chkPublic(float x, float y);			//  5.	Prints value of x and y.
		~Point();							//  6.  Destructor
		
	private:
	
		float itsX;							//	  Private itsX-coordinate.
		float itsY;							//	  Private itsY-coordinate.
		void chkPrivate(float itsX, float itsY);			//  7.  Prints value of itsX and itsY.
};

//************************************
// Constructor that takes user inputted arguments (x, y)
// and never has a return.
//
Point::Point(float x, float y)
{
	cout << endl << endl << endl;
		cout << "  1.  Point::Point(float x, float y) executed." << endl;
	cout << "	  Constructor that takes user inputted arguments (x, y)";
	cout << endl << endl;

	itsX = x;		// Changes value of Private data member itsX to Public x
	itsY = y;		// Changes value of Private data member itsY to Public y

	Point::chkPublic(x, y);		// Prints value of x and y.

	Point::chkPrivate(itsX, itsY);	// Prints value of itsX and itsY.
}

//************************************
// Measured from the origin (itsX, itsY) == (0, 0),
// the user point.itsX defines the horizontal distance.
// And, the user point.itsY defines the vertical distance.
// x_dif is the horizontal line perpendicular to the
// y_dif vertical line and the intersection forms a
// right angle triangle.  Using the Pythagorean theorem  
// return is the length of the hypotenuse
// of a right angle triangle.  The hypotenuse is the distance
// from the origin to the users point.
//
float Point::distance(Point p)		
{
   	cout << endl << endl << endl;
		cout << "  2.  float Point::distance(Point point) executed." << endl;
	cout << "	  The distance from the origin to the users inputted point.";
	cout << endl << endl;

	float x_dif = itsX - p.itsX;
		float y_dif = itsY - p.itsY;
	return sqrt(x_dif * x_dif  +  y_dif * y_dif);
}

//************************************
// Gets user inputted x-coordinate.
//
float Point::x()
{
	cout << endl << endl;
		cout << "  3.  float Point::x() executed." << endl;
	cout << "	  Gets user inputted x-coordinate." << endl;
	cout << "	  Prints value of user inputted x-coordinate." << endl;
	cout << "	  itsX is " << itsX << endl;
	cout << endl << endl;

	return itsX;
}

//************************************
// Gets user inputted y-coordinate.
//
float Point::y()
{
	cout << endl << endl;
		cout << "  4.  float Point::y() executed." << endl;
	cout << "	  Gets user inputted y-coordinate." << endl;
	cout << "	  Prints value of user inputted y-coordinate." << endl;
	cout << "	  itsY is " << itsY << endl;
	cout << endl << endl;

	return itsY;
}

//************************************

void Point::chkPublic(float x, float y)
{
	cout << endl << endl;
		cout << "  5.  void Point::chkPublic(float x, float y)" << endl;
	cout << "	  Prints value of x and y." << endl;
	cout << "	  x is " << x << endl;
	cout << "	  y is " << y << endl;
	cout << endl << endl;
}

//************************************
// Desructor does not take arguments
// and never has a return.
//
Point::~Point()
{
	cout << endl << endl;
		cout << "  6.  Point::~Point() executed Desructor.";
	cout << endl << endl << endl;
}

//************************************

void Point::chkPrivate(float itsX, float itsY)
{
	cout << endl << endl;
		cout << "  7.  void Point::chkPrivate(float itsX, float itsY)" << endl;
	cout << "	  Prints value of itsX and itsY." << endl;
	cout << "	  itsX is " << itsX << endl;
	cout << "	  itsY is " << itsY << endl;
	cout << endl << endl;
}

//************************************

//***START MAIN FUNCTION**************

int main(int argc, char* argv[])
{
		
		int		choice		=	0;
		bool	exitt		=	false;

		//************************************	

		Point origin(0, 0);		// 1st instantiation of class Point.   <==================
								// Assigning zero to the value of both x and y.
								// (0, 0) is the center or origin of the 
								// cartesian coordinate system.
		float x;
		float y;

		do
		{
			cout << endl << endl << endl;
			cout << "**********************************************************************" << endl;
			cout << "  Enter the x and y coordinates for any point." << endl;
			cout << "  Using the Pythagorean theorem and the cartesian coordinae system" << endl;
			cout << "  the program will compute the distance from the origin to your point." << endl;
			cout << endl << endl << endl;
			cout << "  ";
			system("PAUSE");

			system("CLS");

			cout << endl << endl;
			cout << "  Enter the X coordinate for your number then press return  => ";

			while(!(cin >> x))
			{ 
				cin.clear();					//resets any fail state
				cin.ignore(256,'\n');			//discards bad input
				cout << "  Bad Input - Try again" << endl;
			}
			cout << endl << endl;
			cout << "  You entered " << x << flush;

			cout << endl << endl << endl;
			cout << "  ";
			system("PAUSE");

			system("CLS");

			cout << endl << endl;
			cout << "  Enter the Y coordinate for your number then press return  => ";

			while(!(cin >> y))
			{ 
				cin.clear();					//resets any fail state
				cin.ignore(256,'\n');			//discards bad input
				cout << "  Bad Input - Try again" << endl;
			}
			cout << endl << endl;
			cout << "  You entered " << y << flush;

			Point p(x, y);	// 2nd instantiation of class Point.  <======================
							// User input for value of x and y.

			cout << endl << endl << endl;
			cout << "  ";
			system("PAUSE");

			system("CLS");

			cout << endl << endl << endl;
			cout << "  From the origin p(" << origin.x() << ", " << origin.y() << ") ";
			cout << "  to your point p(" << x << ", " << y << ") is ";
			cout << origin.distance(p) << " units of distance." << endl;
			
			//************************************	
			
			cout << endl << endl << endl;
			cout << "  Type the number 1 and press return to run this program again." << endl << endl << endl;
			cout << "  Type any other number and press return to exit ==> ";
					
			while(!(cin >> choice))
			{ 
				cin.clear();					//resets any fail state
				cin.ignore(256,'\n');			//discards bad input
				cout << "  Bad Input - Try again" << endl;
			}
						
			if (choice == 1)
					exitt = false;
					
			else
					exitt = true;
					cout << flush;
					cout << endl << endl << endl;
			cout << "**********************************************************************" << endl;
		}	while(exitt == false);

	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");

	return 0;
}

//***END MAIN FUNCTION**************




The program has a lot of embedded prints to create a console printed audit trail showing when each member function is executed. This approach of having your program print out to the screen when each member function is executed will help you tremendously in learning C++ classes.

III. CLASS DECLARATION

A class is a user defined data type. C++ object-oriented programming (OOP) is a programming style based on the idea of defining your own data types as classes.

Declaring an object of a class type is sometimes referred to as instantiation because you are creating an instance of a class. Instances of a class are referred to as objects. The idea of an object containing the data implicit in its definition, together with the functions that operate on that data, is referred to as encapsulation.

Each object has it's own copy of it's data members. However, each object shares the class member functions.

A class is just a collection of variables combined with a set of related functions. Member variables also known as data members are the class variables. A class also contains functions called member functions or methods which determine what a class can do. The member functions in a class manipulate the member variables. Collectively, the data members and member functions are called the class’s members.

To declare a class, use the class keyword followed by the class name, an opening brace, and then a list of the data members and methods of that class. End the declaration with a closing brace and a semicolon. The statements within the braces are referred to collectively as the class-body. The class member functions will go between the class declaration and the main function. The definition of the class appears outside of the function main() and, therefore, has global scope. This enables you to declare objects in any function of the program.

The class-body of the sample program contains two areas of class access control. The first area is labeled with the keyword public followed by a colon which indicates that the members declared following it are accessible anywhere within the scope of the class object to which they belong. The second area labeled with the keyword private followed by a colon indicates the opposite, namely that the members following it are not accessible from outside the class. If you omit the access specification, the members have the default attribute, private.

As a general rule you should keep the data members of a class private. The private and public keywords enable a feature known as data hiding. C++ ensures that programmers cannot access private data members outside the class unintentionally. To access private data in a class, you must create public functions known as accessor methods. These accessor methods are the member functions that other parts of your program call to get and set private member variables. Accessor functions enable the separation of the details of how the data is stored, from how the data is used.

The class-body contains the declarations of the class member functions. The next step after declaring the class member functions is to define those class member functions.

• IV. MEMBER FUNCTION DEFINITIONS

Now we need to write the class member function definitions. Member functions or methods determine what a class can do. They are normally placed outside the class-body. Therefore, there has to be some way of telling the compiler that the member function belongs to the class. To do this, first you state the return type that will come from the function, or void if nothing will be returned. Next type the name of the class and separate the two with the scope resolution operator, ::, which is formed with two successive colons. This is followed by the name of the function and the function parameters.

The attached program has been written with the following seven member function definitions. The program includes cout prints for each member function. This will allow you to see when each member function is processed and help you to understand the C++ class functionality within this particular program.

1. Point::Point(float x, float y)
"1. Point::Point(float x, float y) executed" will print when this constructor that takes user inputted arguments (x, y) is processed.

2. float Point::distance(Point point)
"2. float Point::distance(Point point) executed" will print when the distance from the origin to the user inputted point is processed.

3. float Point::x()
"3. float Point::x() executed" will print when the user inputted x-coordinate is processed.

4. float Point::y()
"4. float Point::y() executed" will print when the user inputted y-coordinate is processed.

5. void chkPublic(float x, float y);
“5. void chkPublic(float x, float y) executed” will print per your request when you want to see the values stored in the Public x and y variables.

6. Point::~Point()
"6. Point::~Point() executed" will print when the destructor is processed.

7. void chkPrivate(float x, float y);
“7. void chkPublic(float x, float y) executed” will print per your request when you want to see the values stored in the Private itsX and itsY variables.

• V. MAIN FUNCTION

What is a constructor? A class constructor is a special function in a class that is responsible for creating new objects. A class cannot function by itself. Objects must be created from the classes for the classes to be functional. Every object is an independent instance of the class. A class object is created by calling a constructor member function. Note, it is wrong to specify a return type for a constructor, not even void.

What is a destructor? A destructor is a function that destroys an object when it is no longer required or when it goes out of scope. The class destructor is called automatically when an object goes out of scope. The destructor for a class is a member function with the same name as the class, preceded by a tilde (~). The class destructor does not return a value and does not have parameters defined. There can only be one destructor for a class.

Our class Point has one constructor that takes the coordinates of the point being created as arguments.

1. Point origin(0, 0);

1st instantiation of class Point, declaring origin to be an object of type Point and initializing it to have coordinates of (0, 0). Thus assigning zero to the value of both x and y. Note, (0, 0) is the center or origin of the Cartesian coordinate system.

We have followed the general rule requiring keeping the data members of our class private. We have created public function accessor methods called by the main function to get our private member variable values.

The declaration of origin provides coordinates for the parameters and the constructor is called to create and initialize the object for origin.

2. Point p(x,y);

2nd instantiation of class Point is the object p which is initialized with the user inputted values of x and y.

Again, we have followed the general rule requiring keeping the data members of our class private. We created public function accessor methods called by the main function to get our private member variable values.

The declaration of p provides coordinates for parameters and the constructor is called to create and initialize the object for p.

• VI. ANALYSIS

When you build, debug, and run the attached program the first prints you will see scrolling on the console will be member functions 1., 5., and 7. These three member functions will print when the compiler follows the code written in the main() function and creates the first instance of Class Point. This instance or object is named origin. Origin is an object of type Point and is declared at the very beginning of the main() function. Member function 1. is the constructor that takes user inputted arguments (x, y). Origin is declared with zero for both the first and second arguments, x and y respectively. Since origin is declared with Public scope, member function 5. prints the Public values for x, and y. Member function 7. is an accessor method which updates the Private data members itsX and itsY; and prints those values on the console.

The program gives the user a description of what the program is designed to do. Then the program prompts the user to press any key to continue.
The user is prompted to enter a value for the x-coordinate and press return. The user’s input is shown on the console and the program prompts the user to press any key to continue.

The user is prompted to enter a value for the y-coordinate and press return. The user’s input is shown on the console and the program prompts the user to press any key to continue.

After pressing any key to continue, you will see scrolling on the console member functions 1., 5., and 7. These three member functions will print when the compiler follows the code written in the main() function and creates the second instance of Class Point. This instance or object is named p. P is an object of type Point and is declared in the middle of the main() function. Member function 1. is the constructor that takes user inputted arguments (x, y). P is declared with user input for both the first and second arguments, x and y respectively. Since p is declared with Public scope, member function 5. prints the Public values for x, and y. Member function 7. is an accessor method which updates the Private the Private data members itsX and itsY; and prints those values on the console.

The program prompts the user to press any key to continue.

After pressing any key to continue, you will see scrolling on the console member functions 4., 3., 2., and 6. These four member functions will print when the compiler follows the code written in the main() function located just past the creation of the second instance of Class Point. This code prints the value for origin.x and origin.y on the console and then executes member function origin.distance(p) to compute the units of distance from the origin to the users inputted x, y coordinates. Member function 4. will print when the user inputted y-coordinate. Member function 3. will print when the user inputted x-coordinate. Member function 2. will print when the distance from the origin to the user inputted point is computed. And, member function 6. will print when the destructor is processed.

The program prompts the user to press 1 and then press return to run the program again. Or, to press any other number and then press return to exit.

If the user types any number except 1 and presses return, member function 6. will print because the destructor is processed. Then the user is prompted to press any key to continue. When the user presses any key the program exits.

If the user types 1 and presses return member function 6. will print because the destructor is processed. The program gives the user a description of what the program is designed to do. Then the program prompts the user to press any key to continue. And the program process starts all over again.

• VII. CONTACT ME

Please send me comments. As I receive comments I will revise this tutorial.

WHAT YOU HAVE LEARNED IN THIS TUTORIAL

1. You have learned how to declare a class.
2. You have learned how to instantiate a class object.
3. You have learned the basic class vocabulary.
4. You have learned how to define member functions.
5. You have learned how the main() function calls member functions.
6. You have learned how to perform an analysis of a C++ program.

Is This A Good Question/Topic? 2
  • +

Replies To: C++ BEGINNER BARE BONES CLASS TUTORIAL

#2 Paige  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 4
  • Joined: 15-June 09

Posted 15 June 2009 - 09:10 AM

:D
This is absolutely amazing!
Was This Post Helpful? 1
  • +
  • -

#3 Aazor  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 29
  • Joined: 23-November 09

Posted 26 November 2009 - 08:46 PM

just what i was lookin for! thank you so much
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1