Summary: Now we begin our introduction to object-oriented programming in C++. Why have we deferred object-oriented programming in C++ until this chapter? The answer is that the objects we will build will be composed in part of structured program pieces, so we need to establish a basis in structured programming first. Let us briefly explain some key concepts and terminology of object orientation. Object-oriented programming (OOP) encapsulates data (attributes) and functions (behavior) into packages called classes; the data and functions of a class are intimately tied together. A class is like a blueprint. Out of a blueprint, a builder can build a house. Out of a class, a programmer can create an object. One blueprint can be reused many times to make many objects of the same class. Classes have the property of information hiding. This means that although class objects may know how to communicate with one another across well-defined interfaces, classes normally are not allowed to know how other classes are implemented – implementation details are hidden within the classes themselves.
class Time {
public:
Time();
void setTime( int, int, int );
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};
Time sunset, // object of type Times
ArOfTimes[5], // array of Times objects
*ptrTime; // pointer to a Times objects
class Time {
public:
Time();
void setTime( int, int, int );
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};
![]() Figure 1: Diagram of class Time |
#if conditional expression
statements to compile;
#endif
#if !defined(TIME1_H)
#define TIME1_H
class Time {
public:
Time();
void setTime( int, int, int );
void printMilitary();
void printStandard();
private:
int hour;
int minute;
int second;
};
#endif
class Stocks {
public:
double getTotalValue(int iShares, double dCurPrice){
double dCurrentValue;
iNumShares = iShares;
dCurrentPricePerShare = dCurPrice;
dCurrentValue = iNumShares*dCurrentPricePerShare;
return dCurrentValue;
}
private:
int iNumShares;
double dPurchasePricePerShare;
double dCurrentPricePerShare;
};
![]() Figure 2: Diagram of class stock |
#if !defined(STOCKS_H)
#define STOCKS_H
class Stocks{
public:
double getTotalValue(int iShares, double dCurPrice);
private:
int iNumShares;
double dPurchasePricePerShare;
double dCurrentPricePerShare;
};
#endif
#include “stocks.h”
#include<iostream.h>
double Stocks::getTotalValue(int iShares, double dCurPrice){
double dCurrentValue;
iNumShares = iShares;
dCurrentPricePerShare = dCurPrice;
dCurrentValue = iNumShares*dCurrentPricePerShare;
return dCurrentValue;
}
int main(){
Stocks stockPick;
cout << stockPick.getTotalValue(200, 64.25) << endl;
return 0;
}
return-type Class-name::functionName(parameter-list)
{
function body
}
#if !defined(TIME1_H)
#define TIME1_H
class Time {
public:
Time(); // constructor
void setTime( int, int, int ); // set hour, minute, second
void printMilitary(); // print military time format
void printStandard(); // print standard time format
private:
int hour;
int minute;
int second;
};
#endif;
#include “time1.h”
#include <iostream.h>
// Time constructor initializes each data member to zero.
// Ensures all Time objects start in a consistent state.
Time::Time() {
hour = minute = second = 0;
}
void Time::setTime( int h, int m, int s )
{
hour = ( h >= 0 && h < 24 ) ? h : 0;
minute = ( m >= 0 && m < 60 ) ? m : 0;
second = ( s >= 0 && s < 60 ) ? s : 0;
}
void Time::printMilitary()
{
cout << ( hour < 10 ? "0" : "" ) << hour << ":"
<< ( minute < 10 ? "0" : "" ) << minute;
}
void Time::printStandard()
{
cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
<< ":" << ( minute < 10 ? "0" : "" ) << minute
<< ":" << ( second < 10 ? "0" : "" ) << second
<< ( hour < 12 ? " AM" : " PM" );
}
// Driver to test simple class Time
int main()
{
Time t; // instantiate object t of class Time
cout << "The initial military time is ";
t.printMilitary();
cout << "\nThe initial standard time is ";
t.printStandard();
t.setTime( 13, 27, 6 );
cout << "\n\nMilitary time after setTime is ";
t.printMilitary();
cout << "\nStandard time after setTime is ";
t.printStandard();
t.setTime( 99, 99, 99 ); // attempt invalid settings
cout << "\n\nAfter attempting invalid settings:"
<< "\nMilitary time: ";
t.printMilitary();
cout << "\nStandard time: ";
t.printStandard();
cout << endl;
return 0;
}
class Payroll{
public:
Payroll( ){ // constructor function
dFedTax = 0.28;
dStateTax = 0.05;
};
private:
double dFedTax;
double dStateTax;
}
Payroll::Payroll( ){ // constructor function
dFedTax = 0.28;
dStateTax = 0.05;
};
#include <iostream.h>
#include <iomanip.h>
// class declaration section
class Date
{
private:
int month;
int day;
int year;
public:
Date(int = 7, int = 4, int = 2001); // constructor with default values
};
// implementation section
Date::Date(int mm, int dd, int yyyy) // constructor
{
month = mm;
day = dd;
year = yyyy;
cout << "Created a new data object with data values "
<< month << ", " << day << ", " << year << endl;
}
int main()
{
Date a; // declare an object
Date b; // declare an object
Date c(4,1,2002); // declare an object
return 0;
}
TypeName *typeNamPtr;
typeNamePtr = new TypeName;
delete typeNamePtr;
int *pPointer;
pPointer = new int;
delete pPointer;
int *arrayPtr = new int[10];
delete [] arrayPtr;
pointer = new data_type;
int* iPointer;
iPointer = new int;
delete pointer_name;
#include<iostream.h>
int main( )
{
double* pPrimeInterest = new double;
*pPrimeInterest = 0.065;
cout << “The value of pPrimeInterest is: “
<< *pPrimeInterest << endl;
cout << “The memory address of pPimeInterest is:”
<< &pPrimeInterest << endl;
delete pPrimeInterest;
*pPimeInterest = 0.070;
cout << “The value of pPrimeInterest is: “
<< *pPrimeInterest << endl;
cout << “The memory address of pPrimeInterest is: “
<< &pPrimeInterest << endl;
return 0;
}
#include<iostream.h>
class Stocks{
public:
int iNumShares;
double dPurchasePricePerShare;
double dCurrentPricePerShare;
};
double totalValue(Stocks* pCurStock){
double dTotalValue;
dTotalValue = pCurStock->dCurrentPricePerShar*pCurStock->iNumShares;
return dTotalValue;
}
int main( ){
//allocated on the stack with a pointer to the stack object
Stocks stockPick;
Stocks* pStackStock = &stockPick;
pStackStock->iNumShares = 500;
pStackStock-> dPurchasePricePerShare = 10.785;
pStackStock-> dCurrentPricePerShare = 6.5;
cout << totalValue(pStackStock) << endl;
//allocated on the heap
Stocks* pHeapStock = new Stocks;
pHeapStock->iNumShares = 200;
pHeapStock-> dPurchasePricePerShare = 32.5;
pHeapStock-> dCurrentPricePerShare = 48.25;
cout << totalValue(pHeapStock) << endl;
return 0;
}
Stocks* pHeapStock = new Stocks;
#include <iostream.h>
#include <string.h>
// class declaration
class Book
{
private:
char *title; // a pointer to a book title
public:
Book(char * = NULL); // constructor with a default value
void showtitle(); // display the title
};
// class implementation
Book::Book(char *strng)
{
title = new char[strlen(strng)+1]; // allocate memory
strcpy(title,strng); // store the string
}
void Book::showtitle()
{
cout << title << endl;
return;
}
int main()
{
Book book1("DOS Primer"); // create 1st title
Book book2("A Brief History of Western Civilization"); // 2nd title
book1.showtitle(); // display book1's title
book2.showtitle(); // display book2's title
return 0;
}
![]() Figure 3: Object diagram |
If a request is made for either a nonexistent floor or the current floor,
Do nothing
Else if the request is for a floor above the current floor,
Display the current floor number
While not at the designated floor
Increment the floor number
Display the new floor number
End while
Display the ending floor number
Else
Display the current floor number
While not at the designated floor
Decrement the floor number
Display the new floor number
End while
Display the ending floor number
Endif
class Elevator
{
private:
int currentFloor;
public:
Elevator(int = 1); //constructor
void request(int);
};
Elevator::Elevator(int cfloor)
{
currentFloor = cfloor;
}
void Elevator::request(int newfloor)
{
if (newfloor < 1 || newfloor > MAXFLOOR || newfloor == currentFloor)
; // doing nothing
else if (newfloor > currentFloor) // move elevator up
{
cout << “\nStarting at floor “ << currentFloor << endl;
while (newfloor > currentFloor)
{
currentFloor++;
cout << “ Going up – now at floor “ << currentFloor << endl;
}
cout << “ Stopping at floor “ << currentFloor << endl;
}
else // move elevator down
{
cout << “\nStarting at floor “ << currentFloor << endl;
while (newfloor < currentFloor)
{
currentFloor--;
cout << “ Going down – now at floor “ << currentFloor << endl;
}
cout << “ Stopping at floor “ << currentFloor << endl;
}
return;
}
Elevator a(7);
Elevator a;
#include <iostream.h>
const int MAXFLOOR = 15;
//class declaration
class Elevator
{
private:
int currentFloor;
public:
Elevator(int = 1); //constructor
void request(int);
};
// implementation section
Elevator::Elevator(int cfloor)
{
currentFloor = cfloor;
}
void Elevator::request(int newfloor)
{
if (newfloor < 1 || newfloor > MAXFLOOR || newfloor == currentFloor)
; // doing nothing
else if (newfloor > currentFloor) // move elevator up
{
cout << “\nStarting at floor “ << currentFloor << endl;
while (newfloor > currentFloor)
{
currentFloor++;
cout << “ Going up – now at floor “ << currentFloor << endl;
}
cout << “ Stopping at floor “ << currentFloor << endl;
}
else // move elevator down
{
cout << “\nStarting at floor “ << currentFloor << endl;
while (newfloor < currentFloor)
{
currentFloor--;
cout << “ Going down – now at floor “ << currentFloor << endl;
}
cout << “ Stopping at floor “ << currentFloor << endl;
}
return;
}
int main()
{
Elevator a; // declare 1 object of type Elevator
a.request(6);
a.request(3);
return 0;
}
![]() Figure 4: Output of program |
Comments, questions, feedback, criticisms?