Page 1 of 1

C++ BEGINNER BARE BONES CLASS TUTORIAL PART IV C++ BEGINNER BARE BONES CLASS TUTORIAL PART IV 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 06 August 2009 - 02:37 PM

C++ BEGINNER BARE BONES CLASS TUTORIAL PART IV


CONTENTS:
• I. ASSUMPTIONS
• II. INTRODUCTION
• III. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY POINTER
• IV. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY REFERENCE
• V. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY REFERENCE WITH A POINTER ARGUMENT

WHAT YOU WILL LEARN IN THIS TUTORIAL:
1. You will learn how to pass C++ class objects to functions by pointers.
2. You will learn how to pass C++ class objects to functions by reference.
3. You will learn how to pass C++ class objects to functions by
reference with a pointer argument.

• I. ASSUMPTIONS

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

• II. INTRODUCTION

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

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 IV
//Featuring passing a C++ class object
//to a function by reference with a 
//pointer argument.
//**************************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fixed;
using std::exit;
using std::ifstream;
using std::ios;
using std::left;
using std::right;
using std::ofstream;
using std::ostream;
using std::setw;
using std::showpoint;
using std::setprecision;
using std::string;

#endif  //CALC_ERROR_H

class CAccountsReceivable
{
public:

	//Constructor.
	CAccountsReceivable( int = 0, string = "", string = "", double = 0.0 );  

	//Accessor function for account number.
	void m_SetAccountNumber( int );
	int  m_GetAccountNumber( ) const;

	//Accessor function for last name.
	void m_SetLastName( string );
	string m_GetLastName( ) const;

	//Accessor function for first name.
	void m_SetFirstName( string );
	string m_GetFirstName( ) const;

	//Accessor function for balance.
	void m_SetBalance( double );
	double m_GetBalance( ) const;

	//Creates random access file, blank records.
	void m_WritesBlankAccountsReceivableRecords( CAccountsReceivable * );

	//Destructor.		
	~CAccountsReceivable();

private:

	int	accountNumber;
	char   lastName[ 15 ];
	char   firstName[ 10 ];
	double balance;
};

//************************************
//Constructor
//************************************	
CAccountsReceivable::CAccountsReceivable(int accountNumberValue,
										 string lastNameValue, string firstNameValue, double balanceValue )
{
	m_SetAccountNumber( accountNumberValue );
	m_SetLastName( lastNameValue );
	m_SetFirstName( firstNameValue );
	m_SetBalance( balanceValue );
}

//************************************
//Get account number value.
//************************************
int  CAccountsReceivable::m_GetAccountNumber( ) const
{
	return accountNumber;
}

//************************************
//Set account number value.
//************************************
void CAccountsReceivable::m_SetAccountNumber( int accountNumberValue )
{
	accountNumber = accountNumberValue;
}

//************************************
//Get last name value.
//************************************
string  CAccountsReceivable::m_GetLastName( ) const
{
	return lastName;
}

//************************************
//Set last name value.
//************************************
void CAccountsReceivable::m_SetLastName( string lastNameString )
{
	const char *lastNameValue = lastNameString.data();
	int length = lastNameString.size();
	length = ( length < 15 ? length : 14 );
	strncpy_s( lastName, lastNameValue, length );
	lastName[ length ] = '\0';
}

//************************************
//Get first name value.
//************************************
string  CAccountsReceivable::m_GetFirstName( ) const
{
	return firstName;
}

//************************************
//Set first name value.
//************************************
void CAccountsReceivable::m_SetFirstName( string firstNameString )
{
	const char *firstNameValue = firstNameString.data();
	int length = firstNameString.size();
	length = ( length < 10 ? length : 9 );
	strncpy_s( firstName, firstNameValue, length );
	firstName[ length ] = '\0';
}

//************************************
//Get balance value.
//************************************
double CAccountsReceivable::m_GetBalance( ) const
{
	return balance;
}

//************************************
//Set balance value.
//************************************
void CAccountsReceivable::m_SetBalance( double balanceValue )
{
	balance = balanceValue;
}

//************************************
//Writes fixed length records to
//random access file.
//************************************
void CAccountsReceivable::m_WritesBlankAccountsReceivableRecords
( CAccountsReceivable *OBlankAccountsReceivable ) 
{
	ofstream outAccountsReceivable( "AccountsReceivable.dat",
		ios::out | ios::binary );

	if ( !outAccountsReceivable )
	{
		system("CLS");
		cout << endl << endl << endl;
		cerr << "  File could not be opened." << endl;
		cout << endl << endl << endl;
		cout << "  ";
		system("PAUSE");
		exit( 1 );

		for ( int i = 0; i < 100; i++ )
		{
			outAccountsReceivable.write( reinterpret_cast
				< const char * > ( &OBlankAccountsReceivable ),
				sizeof ( CAccountsReceivable ) );
		}
	}

	system("CLS");
	cout << endl << endl << endl;
	cout << "  Congratulations you successfully created a random access file! " << endl << endl << endl;
	cout << endl << endl << endl;
	cout << "  ";
	system ("PAUSE");
}

//************************************
//Destructor
//************************************
CAccountsReceivable::~CAccountsReceivable()  
{

}

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

	do
	{
		system("CLS");
		cout << endl << endl << endl;
		cout << "  C++ BEGINNER BARE BONES CLASS TUTORIAL PART IV "  << endl << endl;
		cout << "  ----------------------------------------------  "  << endl << endl;
		cout << "	0  Quit, exits program.					   "  << endl << endl;
		cout << "	1  Create Random Access File:				 "  << endl;
		cout << "	   Writes Fixed Length Records To File .	  "  << endl << endl;
		cout << "	2  Write To Random Access File.			   "  << endl << endl;
		cout << "	3  Read Random Access File Sequentially.	  "  << endl << endl << endl;

		cout << endl << endl;
		cout << "	Please type a number from 0 to 3 " << endl << endl;
		cout << "	then press Enter ==> ";

		cin >> choice;

		switch(choice)	//start switch
		{
		case (0):
			exitt	 =	true;
			return EXIT_SUCCESS;
			break;

		case (1):
			//************************************
			//Creates the random access file.
			//************************************
			{
				//Instantiates object OBlankAccountsReceivable of type CAccountsReceivable.
				CAccountsReceivable OBlankAccountsReceivable;

				OBlankAccountsReceivable.m_WritesBlankAccountsReceivableRecords
					( &OBlankAccountsReceivable );
			}

			//************************************
			break;

		case (2):
			//************************************
			//Writes to the random access file.
			//************************************
			{
				int	accountNumber;
				char   lastName[ 15 ];
				char   firstName[ 10 ];
				double balance;

				fstream outAccountsReceivable( "AccountsReceivable.dat",
					ios::in | ios::out |ios::binary );

				if ( !outAccountsReceivable )
				{
					system("CLS");
					cout << endl << endl << endl;
					cerr << "  File could not be opened." << endl;
					cout << endl << endl << endl;
					cout << "  ";
					system("PAUSE");
					exit( 1 );
				}

				system("CLS");
				cout << endl << endl << endl;
				cout << "  Please enter customer account number." << endl << endl;
				cout << "  Enter a number from 1 to 100 " << endl << endl;
				cout << "  then press Enter => ";

				//Instantiates object OCustomer of type CAccountsReceivable.
				CAccountsReceivable OCustomer;

				cin >> accountNumber;
				cout << endl << endl << endl;
				cout << "  You entered " << accountNumber;
				cout << endl << endl << endl;
				cout << "  ";
				system ("PAUSE");

				if( accountNumber > 0 && accountNumber <= 100 )
				{
					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer last name." << endl << endl;
					cout << "  Maximum 15 characters, for example Jones" << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> setw( 15 ) >> lastName;
					cout << endl << endl << endl;
					cout << "  You entered " << lastName;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer first name." << endl << endl;
					cout << "  Maximum 10 characters, for example Roy" << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> setw( 10 ) >> firstName;
					cout << endl << endl << endl;
					cout << "  You entered " << firstName;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					system( "CLS" );
					cout << endl << endl << endl;
					cout << "  Please enter customer account balance." << endl << endl;
					cout << "  for example, 1000 " << endl << endl;
					cout << "  and then press Enter => ";
					cin  >> balance;
					cout << endl << endl << endl;
					cout << "  You entered " << balance;
					cout << endl << endl << endl;
					cout << "  ";
					system ("PAUSE");

					OCustomer.m_SetAccountNumber( accountNumber );
					OCustomer.m_SetLastName( lastName );
					OCustomer.m_SetFirstName( firstName );
					OCustomer.m_SetBalance( balance );

					outAccountsReceivable.seekp( ( OCustomer.m_GetAccountNumber( ) - 1 ) *
						sizeof( CAccountsReceivable ) );

					outAccountsReceivable.write( reinterpret_cast< const char * > ( &OCustomer ),
						sizeof( CAccountsReceivable ) );
				}
			}
			//************************************
			break;

		case (3):
			//************************************
			//Read random access file sequentially.
			//************************************
			{
				ifstream inAccountsReceivable( "AccountsReceivable.dat",
					ios::in | ios::binary );

				if ( !inAccountsReceivable )
				{
					system("CLS");
					cout << endl << endl << endl;
					cerr << "  File could not be opened." << endl;
					cout << endl << endl << endl;
					cout << "  ";
					system("PAUSE");
					exit( 1 );
				}

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

				cout << left << setw( 10 ) << "ACCOUNT"
					<< setw ( 16 ) << "LAST NAME" << left 
					<< setw ( 11 ) << "FIRST NAME"
					<< setw ( 10 ) << right << "BALANCE" << endl;

				//Instantiates object OCustomer of type CAccountsReceivable.
				CAccountsReceivable OCustomer;

				inAccountsReceivable.read( reinterpret_cast< char * >
					( &OCustomer ), sizeof( CAccountsReceivable ) );

				while ( inAccountsReceivable && !inAccountsReceivable.eof() )
				{
					if ( OCustomer.m_GetAccountNumber() != 0 )
					{

						cout << endl;
						cout << "  ";

						cout << left << setw( 10 ) << OCustomer.m_GetAccountNumber()
							<< setw ( 16 ) << OCustomer.m_GetLastName() << left 
							<< setw ( 11 ) << OCustomer.m_GetFirstName()
							<< setw ( 10 ) << setprecision( 2 ) << right << fixed
							<< showpoint << OCustomer.m_GetBalance() << endl; 

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

					inAccountsReceivable.read( reinterpret_cast< char * >
						( &OCustomer ), sizeof( CAccountsReceivable ) );
				}

			}
			//************************************	
			break;

		default:
			cout << endl << endl << endl;
			cout << "Switch default error message! ";
			cout << endl << endl << endl;
			system("PAUSE");
			break;
		}

	}while( exitt == false );

	return EXIT_SUCCESS;
}



• III. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY POINTER

What is a pointer? A pointer is a variable that holds a memory address. For the pointer to work properly you must perform the following three steps:

Step 1: Declare and initialize the pointer.

The syntax for declaring and initializing a pointer is as follows:

type *pointer_Name = 0;

In the pointer declaration the pointer asterisk can either follow the type of the object pointed to

double* pB = 0;

or precede the pointer

double *pB = 0;

It is good programming practice to name pointers with the initial letter “p” as shown above.

Step 2: Assign the pointer an address.

First, the variable you plan to point to must be declared and initialized; for example:

double a = 10.00;

Second, the address must be assigned to the pointer.

The syntax for assigning the pointer an address is as follows:

pointer_Name = &variable_name;

For example:

pB = &a;

Step 3: Use the pointer asterisk dereference or indirection operator to get 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. A pointer provides indirect access to the value of the variable whose address it stores. However, always remember, a pointer must be assigned a memory address of a value before dereference operations will work.

The syntax for dereference or indirection is as follows:

*pointer_Name;

For example:

cout << *ptrB;

Displays 10.00

• IV. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY REFERENCE

The syntax for pass by reference is as follows:

type className::m_FunctionName(const className& rhs) const{…}

Follow the parameter’s type in the function prototype with an ampersand & to indicate that a function parameter is passed by reference.

Objects may be passed to functions in just the same way that any other type of variable can be passed to functions. A function may return an object to a caller. And, you can assign one object to another, assuming both objects are of the same type.

Reference Rules:

1. Do not make copies of the original value.

2. Pass a pointer to the original value to any function that you want to be able to use or change the original value.

3. After you pass the pointer can have the function dereference the pointer to use or change the original value.

4. Always remember, when using references, when you have your function dereference the pointer and change the value, you are changing the original value. If you want a function to have a local copy to change safely, you must have your function explicitly allocate and initialize a local copy.

A reference parameter is an alias, another name for its corresponding argument in a function call. It is good programming practice to prefix reference names with the letters “ref.”

Pass all objects to class methods and constructors as references unless you plan to reassign the objects or use null values for the objects. Reference variables must be initialized in their declarations and cannot be reassigned as aliases to other variables.

If you plan to do reassignments you must use pointers instead of references. References cannot be null, if you plan to have null values for the object you must use pointers instead of references.

Due to scope issues, if you return a reference to a variable declared in a called function, the variable must be declared static within that function.
When accessing members of a class given a reference to an object, use the . dot operator instead of the -> arrow operator.

• V. PASSING C++ CLASS OBJECTS TO FUNCTIONS BY REFERENCE WITH A POINTER ARGUMENT

Passing C++ class objects to functions by reference with a pointer argument combines the above sections III. and IV.

1. The syntax for the prototype is as follows:

type function_Name( class_Name * );

The syntax for the prototype used in the attached example program is as follows:

void m_WritesBlankAccountsReceivableRecords( CAccountsReceivable * );

2. The syntax for the function definition is as follows:

type class_Name::function_Name( class_Name *objectName ) {…};

The syntax for the function definition used in the attached example program is as follows:

void CAccountsReceivable::m_WritesBlankAccountsReceivableRecords( CAccountsReceivable *OBlankAccountsReceivable ) {…};

3. The syntax for the function call is as follows:

objectName.function_Name( &objectName );

The syntax for the function call used in the attached example program is as follows:

OBlankAccountsReceivable.m_WritesBlankAccountsReceivableRecords( &OBlankAccountsReceivable );

WHAT YOU HAVE LEARNED IN THIS TUTORIAL:
1. You have learned how to pass C++ class objects to functions by pointers.
2. You have learned how to pass C++ class objects to functions by reference.
3. You have learned how to pass C++ class objects to functions by reference with a pointer argument.

Is This A Good Question/Topic? 2
  • +

Replies To: C++ BEGINNER BARE BONES CLASS TUTORIAL PART IV

#2 genomega  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 3
  • Joined: 17-May 10

Posted 18 May 2010 - 04:03 PM

A good useful real world tutorial, thanks a lot.

I made a few changes to compile it for linux, well worth the effort though.
Was This Post Helpful? 1
  • +
  • -

#3 Elcric  Icon User is offline

  • D.I.C Regular
  • member icon

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

Posted 25 May 2010 - 02:02 AM

Hello Genomega,

Thank you very much!

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1