Page 1 of 1

C++ BEGINNER BARE BONES CLASS TUTORIAL PART III C++ BEGINNER BARE BONES CLASS TUTORIAL PART III Rate Topic: -----

#1 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

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

Posted 28 July 2009 - 06:19 AM

C++ BEGINNER BARE BONES CLASS TUTORIAL PART III


CONTENTS:
• I. ASSUMPTIONS
• II. INTRODUCTION
• III. COPY CONSTRUCTOR VOCABUARY
• IV. CONSTRUCTORS
• V. OBJECTS
• VI. DATA MEMBERS
• VII. DESTRUCTORS
• VIII. MAIN FUNCTION

WHAT YOU WILL LEARN IN THIS TUTORIAL:

1. You will learn how to use constructors to specify initial values for object data members.

2. You will learn how to use object instantiation to pass data to constructors.

3. You will learn how to use Set and Get member functions to specify initial values for object data members.

4. You will learn the beginner copy constructor vocabulary.

5. You will learn how to create and use copy constructors.

• I. ASSUMPTIONS

I assume you have a C++ compiler and you want to learn more about C++ classes.

• II. INTRODUCTION

Hello; nice to meet you! Welcome to the “C++ Beginner Bare Bones Class Tutorial Part III.”

Please copy and paste the attached example program into a file your compiler can read. Then build, compile, and debug the example program. Following along, back and forth, between the tutorial and your copy of the example program will help you understand the example program functionality.

//*****************************************************
//C++ BEGINNER BARE BONES CLASS TUTORIAL PART III. 
//The tutorial includes the following compound interest
//example which features copy constructors.
//*****************************************************
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>

using namespace std;

class CBank
{
	public:

			   
			   CBank( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber );  //Constructor.
			   CBank(const CBank& OCharacter3);  //Copy constructor.
		void   m_SetCustomerAccount( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber );
		void   m_GetCustomerAccount(  double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber );
		void   m_displayInterestEarned( );
			   ~CBank();
	private:

		double itsAmount;
		double itsInterestEarned;
		double itsInterestRate;
		double itsPrinciple;
		int itsYearsOnDeposit;
		int itsCustomerNumber;
		
};

CBank::CBank(const CBank& OCharacter3)  //Copy constructor.
{
	itsAmount = OCharacter3.itsAmount;
	itsInterestEarned = OCharacter3.itsInterestEarned;
	itsInterestRate = OCharacter3.itsInterestRate;
	itsPrinciple = OCharacter3.itsPrinciple;
	itsYearsOnDeposit = OCharacter3.itsYearsOnDeposit;
}

CBank::CBank( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber )
{
	m_SetCustomerAccount( amount, interestEarned, interestRate, principle, yearsOnDeposit, customerNumber ); 
}

void CBank::m_GetCustomerAccount( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber )
{
	double xAmount = 0.0;
	double xInterestRate = 0.0;
	double xPrinciple = 0.0;
	int	xYearsOnDeposit = 0;
	
	itsCustomerNumber = customerNumber;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type the amount you are depositing," << endl << endl;
	cout << "  then press Enter." << endl << endl;
	cout << "  For example 1000 ==> ";
	cin  >> xPrinciple;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsPrinciple = xPrinciple;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type the number of years you are investing your deposit," << endl << endl;
	cout << "  then press Enter." << endl << endl;   
	cout << "  For example 1 ==> ";
	cin  >> xYearsOnDeposit;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsYearsOnDeposit = xYearsOnDeposit;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type your investment interest rate," << endl << endl;
	cout << "  then press Enter." << endl << endl;   
	cout << "  For example .05 ==> ";
	cin  >> xInterestRate;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsInterestRate = xInterestRate;

	 for(int year = 1; year <= xYearsOnDeposit; year++)
		{	
			xAmount = xPrinciple * pow((1 + xInterestRate), year);
		}

	itsAmount = xAmount;

	itsInterestEarned = (xPrinciple - xAmount);
}

void CBank::m_SetCustomerAccount(  double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber )
{
	itsAmount = amount;
	itsInterestEarned = interestEarned;
	itsInterestRate = interestRate;
	itsPrinciple = principle;
	itsYearsOnDeposit = yearsOnDeposit;
	itsCustomerNumber = customerNumber;

	if (itsCustomerNumber == 3)
	{
		customerNumber = 3;
		m_GetCustomerAccount( amount, interestEarned, interestRate, principle, yearsOnDeposit, customerNumber );
	}
}

void CBank::m_displayInterestEarned()
{
	cout << endl << endl << endl;
	cout << "	   COMPOUND INTEREST IS INTEREST THAT EARNS INTEREST" << endl << endl << endl;
	cout << "  CUSTOMER" << itsCustomerNumber << endl << endl;
	cout << "  AMOUNT DEPOSITED:  " << itsPrinciple << endl << endl;
	cout << "  INTEREST RATE:	 " << itsInterestRate << endl << endl;
	cout << "  YEARS LEFT IN BANK:  " << itsYearsOnDeposit << endl << endl << endl;
	cout << "  END OF		 TOTAL AMOUNT" << "	   TOTAL INTEREST" << endl;
	cout << "   YEAR" << setw(21) << " ON DEPOSIT" << setw(18) << "EARNED" << endl;
	cout << "   ----" << setw(21) << " ----------" << setw(18) << "------" << endl;
	cout << fixed << setprecision(2);
		for(int year = 1; year <= itsYearsOnDeposit; year++)
		{
			itsAmount = itsPrinciple * pow((1 + itsInterestRate), year);  //pow(base, exponent)
			cout << "   " << setw(4) << year << setw(21) << itsAmount << setw(18) << (itsAmount-itsPrinciple)<< endl;
		}
}

CBank::~CBank()
{
	
}

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
	int	 choice   =	0;
	bool	exit	=	false;
	//************************************
	
	do
	{
		system( "CLS" );
		CBank OCustomer1( 0.00, 0.00, 0.00, 0.00, 0, 1 );
		OCustomer1.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");
		
		system( "CLS" );
		CBank OCustomer2( 1050.00, 50.00, .05, 1000.00, 1, 2 );
		OCustomer2.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");

		system( "CLS" );
		CBank OCustomer3( 0.00, 0.00, 0.00, 0.00, 0, 3 );
		OCustomer3.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");

		system( "CLS" );
		CBank OCustomer4( 0.00, 0.00, 0.00, 0.00, 0, 4 );
		//Copy OCustomer3 interestRate, principle, and yearsOnDeposit
		//to OCustomer4, then compute the OCustomer4 interestEarned and amount. 

		OCustomer4 = OCustomer3;  //Calls copy constructor.

		OCustomer4.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");
		
		//************************************
		system( "CLS" );
		cout << endl << endl << endl;
		cout << "  Type the number 1 and press return ";
		cout << "to run the program again.  " << endl << endl;
		cout << "  Type 0 and press return to exit. ==> ";
		cin >> choice;
		if ( choice == 0 )
		{
			OCustomer1.~CBank();  //These destructors are not really necessary.
			OCustomer2.~CBank();  //Just shown for demonstration purposes.
			OCustomer3.~CBank();
			OCustomer4.~CBank();
			EXIT_SUCCESS;
		}
		if ( choice == 1 )
			exit = false;
		else
		{
			OCustomer1.~CBank();  //These destructors are not really necessary.
			OCustomer2.~CBank();  //Just shown for demonstration purposes.
			OCustomer3.~CBank();
			OCustomer4.~CBank();
			exit = true;
		}
	}while( exit == false );

	return EXIT_SUCCESS;
}




• III. COPY CONSTRUCTOR VOCABULARY

1. What is a pointer?

To use pointers you should understand the difference between a pointer; the address the pointer contains; and the value at the address the pointer contains.

Step 1: Declare and initialize the pointer.

A pointer is a variable that holds a memory address.
The syntax for declaring and initializing a pointer is as follows:

type *pointer_Name = 0;

It is good programming practice to name pointers with an initial p; for example:

double *pB = 0;

In the pointer declaration the pointer asterisk follows the type of the object pointed to.

Step 2: Assign the pointer an address.

Before a pointer can contain an address the address must be assigned to the pointer.

double a = 10.00;

pB = &a;

Step 3: Pointer dereference or indirection to get the value.

A pointer provides indirect access to the value of the variable whose address it stores. As a dereference or indirection operator the pointer asterisk indicates that the value at the memory address is to be accessed instead of the address itself.

cout << *pB;

Displays 10.00

2. What is a try block?

Exceptions arise due to predictable problems such as running out of memory or disk space. You use a try block to tell the compiler to watch code that might create exceptions during execution. You create a try block by adding the keyword try and braces around any code which could cause exceptions

The keyword throw can be used to test a try block. The syntax for the keyword throw is as follows:

throw exception;

3. What is a catch block?

When a try block is executed, if an exception occurs, it is said to be thrown. Thrown exceptions can then be caught with a catch block. A catch block begins with the keyword catch, followed by an exception type in parentheses, followed by an opening brace, and ending with a closing brace.

When an exception is thrown it is sent to the first catch block following the try block. The compiler executes the catch block if the exception type in the catch block’s parameter parentheses matches the thrown exception. If there is no match the next catch block’s exception parameter parentheses is checked, and so on, until a match is found and that matching catch block is executed. When you code a catch block you can include a specific exception as a parameter in the catch block’s parameter parentheses or use the ellipsis … as an all inclusive exception parameter in the catch block’s parameter parentheses.

4. What is the keyword const?

You use the keyword const to define constants, this allows the compiler to enforce the usage of the type.

5. What is put()?

put() is a function that writes a single character to the output device.

6. What is get()?

get() is a function that obtains a single character from an input device.

7. What is overload?

When you overload a method you create more than one method with the same name but with a different signature.

8. What is override?

When you override a method you create a method in a derived class with the same name as the method in the base class and the same signature.

9. What is a base class?

A class that adds new functionality to an existing class is said to derive from that original class. The original class is said to be the new class’s base class.

Base class initialization can be performed during class initialization by writing the base class name followed by the parameters expected by the base class.

10. What is a derived class?

A class that adds new functionality to an existing class is said to derive from that original class.

11. What is a signature?

The signature is the function prototype other than the return type: the name of the function, the parameter list, and the keyword const if it is used.

In the attached example program the class of the object being copied is CBank, and the copy constructor’s signature is:

CBank::CBank (const CBank &);

12. What is a shallow copy?

Bitwise, bit-by-bit, copies of objects are shallow copies. If A and B are shallow copies, they are not separate and distinct objects, they both have the same memory storage location. Changing the value of A makes B have the same value. A shallow copy is fast when compared to a deep copy.

13. What is a deep copy?

A deep copy is not a bitwise, bit-by-bit, copy. If A and B are deep copies, they are separate and distinct objects, each has its own unique memory storage location. Changing the value of A does not change the value of B. A deep copy is comparatively slower than a shallow copy.

14. What is a lazy copy?

A lazy copy is initially a shallow copy. It has the speed of a shallow copy. When the object that was lazy copied is needed the compiler does a deep copy before use.

15. What is rhs?

rhs means right-hand-side of the equal sign. And, lhs means left hand side of the equal sign.

• IV. CONSTRUCTOR

A constructor is a function with the same name as the class. The tasks performed by a constructor are to create a new instance of the class and initialize the data members of the new instance.

Constructors are normally declared public and defined with the same name as the class. If a class does not include a constructor the compiler includes a default constructor with no parameters and no return type. Constructors can not specify a return type, not even void. Constructors cannot be virtual. The compiler default constructor allocates memory for the class object; however, it does not initialize the class object’s data members.

A class can have several constructors.

1. Constructor with parameters.

Using data members before they have been properly initialized can cause logic errors. It is good programming practice to declare a constructor that initializes your class object data members with meaningful values each time a new object of the class is created, instantiated. A constructor specifies in its parameter list the data it requires to initialize the class object’s data members.

CBank( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber );



When you create a new object you place the data required by the constructor in the parentheses following the objects name.

CBank OCustomer2( 1050.00, 50.00, .05, 1000.00, 1, 2 );



2. Copy constructor

The compiler automatically creates an implicit copy constructor for each class. The copy constructor created by the programmer is an explicit copy constructor. A copy constructor is a special constructor that allows the programmer to create a new object from an existing object by initialization. The copy constructor creates a new object of the same class and copies the value of the data members from the calling object into the new object’s data members.

The syntax for a copy constructor is as follows:

Class_name::Class_name(const Class_name & Object_Being_Copied);

The syntax for the copy constructor used in the example program is as follows:

CBank::CBank(const CBank& OCharacter3);

C++ performs a bitwise, bit-by-bit, copy when one object is used to initialize another. An identical copy of the initializing object is created in the target object. The target object does not create its own memory it uses the same memory as the initializing object. This also happens when a copy of an object is made when it is passed as an argument to a function, and when a temporary object is made as a return value from a function. Using a copy constructor solves this same memory usage problem by bypassing the bitwise, bit-by-bit, copy.

The assignment operator copies to existing objects, and the copy constructor copies to newly created objects. If a new object has to be created before the copying can occur, the copy constructor is used. If a new object does not have to be created before the copying can occur, the assignment operator is used.

Assignment and initialization are two situations in which the value of one object is given to another. The copy constructor applies only to initializations.

There are three general cases where the copy constructor is called instead of the assignment operator:

First, when a temporary object is made as a return value from a function;
for example, a = function();.

Second, when a copy of an object is made to be passed by value as a parameter to a function; for example, function(a);.

Third, when one object initializes another through a declaration; for example, class instantiation object b = a;.

In each of these cases, a new variable needs to be created before the values can be copied.

A copy constructor looks just like a normal constructor that takes a class data member parameter; however, the parameter must be passed by reference, and not by value.

The following is a copy constructor used in the attached example program.

CBank::CBank(const CBank& OCharacter3)  //Copy constructor.
{
	itsAmount = OCharacter3.itsAmount;
	itsInterestEarned = OCharacter3.itsInterestEarned;
	itsInterestRate = OCharacter3.itsInterestRate;
	itsPrinciple = OCharacter3.itsPrinciple;
	itsYearsOnDeposit = OCharacter3.itsYearsOnDeposit;
}



• V. OBJECTS

C++ allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor function.

CBank( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber );



system( "CLS" );
CBank OCustomer2( 1050.00, 50.00, .05, 1000.00, 1, 2 );
OCustomer2.m_displayInterestEarned();
cout << endl << endl << endl;
cout << "  ";
system("PAUSE");



An object is an individual instance of a class. When a program creates, instantiates, an object of a class, its private data members are encapsulated, hidden, and can be accessed only by member functions of the object’s class. Set and Get member functions of the object’s class allow clients of a class to access the hidden data.

• VI. DATA MEMBERS

Member variables also known as data members are the class variables. As a general rule you should keep the data members of a class private.

private:

		double itsAmount;
		double itsInterestEarned;
		double itsInterestRate;
		double itsPrinciple;
		int itsYearsOnDeposit;
		int itsCustomerNumber;
		
};



The private and public keywords enable a feature known as data hiding. 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.

void CBank::m_GetCustomerAccount( double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber )
{
	double xAmount = 0.0;
	double xInterestRate = 0.0;
	double xPrinciple = 0.0;
	int	xYearsOnDeposit = 0;
	
	itsCustomerNumber = customerNumber;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type the amount you are depositing," << endl << endl;
	cout << "  then press Enter." << endl << endl;
	cout << "  For example 1000 ==> ";
	cin  >> xPrinciple;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsPrinciple = xPrinciple;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type the number of years you are investing your deposit," << endl << endl;
	cout << "  then press Enter." << endl << endl;   
	cout << "  For example 1 ==> ";
	cin  >> xYearsOnDeposit;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsYearsOnDeposit = xYearsOnDeposit;

	system( "CLS" );
	cout << endl << endl << endl;
	cout << "  Please type your investment interest rate," << endl << endl;
	cout << "  then press Enter." << endl << endl;   
	cout << "  For example .05 ==> ";
	cin  >> xInterestRate;
	cout << endl << endl << endl;
	cout << "  ";
	system("PAUSE");
	itsInterestRate = xInterestRate;

	 for(int year = 1; year <= xYearsOnDeposit; year++)
		{	
			xAmount = xPrinciple * pow((1 + xInterestRate), year);
		}

	itsAmount = xAmount;

	itsInterestEarned = (xPrinciple - xAmount);
}

void CBank::m_SetCustomerAccount(  double amount, double interestEarned, double interestRate, double principle, int yearsOnDeposit, int customerNumber )
{
	itsAmount = amount;
	itsInterestEarned = interestEarned;
	itsInterestRate = interestRate;
	itsPrinciple = principle;
	itsYearsOnDeposit = yearsOnDeposit;
	itsCustomerNumber = customerNumber;

	if (itsCustomerNumber == 3)
	{
		customerNumber = 3;
		m_GetCustomerAccount( amount, interestEarned, interestRate, principle, yearsOnDeposit, customerNumber );
	}
}



As shown above, each member function call tells the object to perform a task.

• VII. DESTRUCTORS

The name of a destructor for a class is the tilde character ~ followed by the class name. A destructor receives no parameters and returns no value. A destructor may not specify a return type, not even void. A destructor must be public. Since a destructor has no parameters, a class can only have one destructor; however, this destructor can be called many times. If you do not provide a destructor the compiler provides an empty destructor with no parameters and no return type.

The destructor is called automatically by the compiler when the program execution leaves the scope within which an object was instantiated.

• VIII. MAIN FUNCTION

A function in a class is known as a member function and performs one of the class’s tasks. An empty set of parentheses following a member function name indicates the member function does not require any additional data to perform its task. Control statements specify the order in which the member function’s tasks are performed. Conventional programming practice is to start the name of a member function with a lower case letter and use a capital letter to start each additional word in the member function name.

//************************************
// MAIN() FUNCTION.
//************************************
int main(int argc, char* argv[])
{
	int	 choice   =	0;
	bool	exit	=	false;
	//************************************
	
	do
	{
		system( "CLS" );
		CBank OCustomer1( 0.00, 0.00, 0.00, 0.00, 0, 1 );
		OCustomer1.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");
		
		system( "CLS" );
		CBank OCustomer2( 1050.00, 50.00, .05, 1000.00, 1, 2 );
		OCustomer2.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");

		system( "CLS" );
		CBank OCustomer3( 0.00, 0.00, 0.00, 0.00, 0, 3 );
		OCustomer3.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");

		system( "CLS" );
		CBank OCustomer4( 0.00, 0.00, 0.00, 0.00, 0, 4 );
		//Copy OCustomer3 interestRate, principle, and yearsOnDeposit
		//to OCustomer4, then compute the OCustomer4 interestEarned and amount. 

		OCustomer4 = OCustomer3;  //Calls copy constructor.

		OCustomer4.m_displayInterestEarned();
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");
		
		//************************************
		system( "CLS" );
		cout << endl << endl << endl;
		cout << "  Type the number 1 and press return ";
		cout << "to run the program again.  " << endl << endl;
		cout << "  Type 0 and press return to exit. ==> ";
		cin >> choice;
		if ( choice == 0 )
		{
			OCustomer1.~CBank();  //These destructors are not really necessary.
			OCustomer2.~CBank();  //Just shown for demonstration purposes.
			OCustomer3.~CBank();
			OCustomer4.~CBank();
			EXIT_SUCCESS;
		}
		if ( choice == 1 )
			exit = false;
		else
		{
			OCustomer1.~CBank();  //These destructors are not really necessary.
			OCustomer2.~CBank();  //Just shown for demonstration purposes.
			OCustomer3.~CBank();
			OCustomer4.~CBank();
			exit = true;
		}
	}while( exit == false );

	return EXIT_SUCCESS;
}



A class member function is called by following an object name with the dot . operator, followed by the member function name and a set of parentheses listing the member function’s arguments.

WHAT YOU HAVE LEARNED IN THIS TUTORIAL:

1. You have learned how to use constructors to specify initial values for object data members.

2. You have learned how to use object instantiation to pass data to constructors.

3. You have learned how to use Set and Get member functions to specify initial values for object data members.

4. You have learned the beginner copy constructor vocabulary.

5. You have learned how to create and use copy constructors.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1