Objects and Classes

Abstraction and Classes



// stocks.cpp

#include <iostream.h>
#include <stdlib.h>	// for exit()
#include <string.h> // for strcpy()

class Stock
{
private:
	char company[30];
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }
public:
	void acquire(const char * co, int n, double pr);
	void buy(int num, double price);
	void sell(int num, double price);
	void update(double price);
	void show();
};


void Stock::acquire(const char * co, int n, double pr)
{
	strcpy(company, co);
	shares = n;
	share_val = pr;
	set_tot();
}

void Stock::buy(int num, double price)
{
	shares += num;
	share_val = price;
	set_tot();
}

void Stock::sell(int num, double price)
{
	if (num > shares)
	{
		cerr << "You can't sell more than you have!\n";
		exit(1);
	}
	shares -= num;
	share_val = price;
	set_tot();
}

void Stock::update(double price)
{
	share_val = price;
	set_tot();
}

void Stock::show()
{
	cout << "Company: " << company
		<< "  Shares: " << shares << '\n'
		<< "  Share Price: $" << share_val
		<< "  Total Worth: $" << total_val << '\n';
}

int main(void)
{
	Stock stock1;

	stock1.acquire("NanoSmart", 20, 12.50);
	cout.precision(2);			// #.## format
	cout.setf(ios::fixed);		// #.## format
	cout.setf(ios::showpoint);	// #.## format
	stock1.show();
	stock1.buy(15, 18.25);
	stock1.show();
	return 0;
}



Class Constructors and Desctuctors



// stock1.h

#ifndef _STOCK1_H_
#define _STOCK1_H_

class Stock
{
private:
	char company[30];
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }
public:
	Stock();		// default constructor
	Stock(const char * co, int n = 0, double pr = 0.0);
	~Stock();		// nosey destructor
	void buy(int num, double price);
	void sell(int num, double price);
	void update(double price);
	void show();
};

#endif


// stock1.cpp 	// Stock class methods

#include <iostream.h>
#include <stdlib.h>	// for exit()
#include <string.h> // for strcpy()
#include "stock1.h"

// constructors
Stock::Stock()		// default constructor
{
	strcpy(company, "no name");
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

Stock::Stock(const char * co, int n, double pr)
{
	strcpy(company, co);
	shares = n;
	share_val = pr;
	set_tot();
}

// class destructor
Stock::~Stock()		// class destructor
{
	cout << "Bye, " << company << "!\n";
}

// other methods
void Stock::buy(int num, double price)
{
	shares += num;
	share_val = price;
	set_tot();
}

void Stock::sell(int num, double price)
{
	if (num > shares)
	{
		cerr << "You can't sell more than you have!\n";
		exit(1);
	}
	shares -= num;
	share_val = price;
	set_tot();
}

void Stock::update(double price)
{
	share_val = price;
	set_tot();
}

void Stock::show()
{
	cout << "Company: " << company
		<< "  Shares: " << shares << '\n'
		<< "  Share Price: $" << share_val
		<< "  Total Worth: $" << total_val << '\n';
}


// usestok1.cpp -- use the Stock class

#include <iostream.h>
#include "stock1.h"

int main(void)
{
// using constructors to create new objects
	Stock stock1("NanoSmart", 12, 20.0);            // syntax 1
	Stock stock2 = Stock ("Boffo Objects", 2, 2.0); // syntax 2

	cout.precision(2);			// #.## format
	cout.setf(ios::fixed, ios::floatfield);		// #.## format
	cout.setf(ios::showpoint);	// #.## format

	stock1.show();
	stock2.show();
	stock2 = stock1;				// object assignment

// using a constructor to reset an object
	stock1 = Stock("Nifty Foods", 10, 50.0);	// temp object

	cout << "After stock reshuffle:\n";
	stock1.show();
	stock2.show();
	return 0;
}



Knowing Your Objecys: The this Pointer



// stock2.h

#ifndef _STOCK2_H_
#define _STOCK2_H_

class Stock
{
private:
	char company[30];
	int shares;
	double share_val;
	double total_val;
	void set_tot() { total_val = shares * share_val; }
public:
	Stock();		// default constructor
	Stock(const char * co, int n, double pr);
	~Stock() {}		// do-nothing destructor
	void buy(int num, double price);
	void sell(int num, double price);
	void update(double price);
	void show() const;
	const Stock & topval(const Stock & s) const;
};

#endif



// stock2.cpp 	// Stock class methods

#include <iostream.h>
#include <stdlib.h>	// for exit()
#include <string.h> // for strcpy()
#include "stock2.h"

// constructors
Stock::Stock()
{
	strcpy(company, "no name");
	shares = 0;
	share_val = 0.0;
	total_val = 0.0;
}

Stock::Stock(const char * co, int n, double pr)
{
	strcpy(company, co);
	shares = n;
	share_val = pr;
	set_tot();
}

void Stock::buy(int num, double price)
{
	shares += num;
	share_val = price;
	set_tot();
}

void Stock::sell(int num, double price)
{
	if (num > shares)
	{
		cerr << "You can't sell more than you have!\n";
		exit(1);
	}
	shares -= num;
	share_val = price;
	set_tot();
}

void Stock::update(double price)
{
	share_val = price;
	set_tot();
}

void Stock::show() const
{
	cout << "Company: " << company
		<< "  Shares: " << shares << '\n'
		<< "  Share Price: $" << share_val
		<< "  Total Worth: $" << total_val << '\n';
}

const Stock & Stock::topval(const Stock & s) const
{
	if (s.total_val > total_val)
		return s;
	else
		return *this;
}



An Array of Objects



// usestok2.cpp -- use the Stock class

#include <iostream.h>
#include "stock2.h"

const int STKS = 4;
int main(void)
{
// create an array of initialized objects
	Stock stocks[STKS] = {
		Stock("NanoSmart", 12, 20.0),
		Stock("Boffo Objects", 200, 2.0),
		Stock("Monolithic Obelisks", 130, 3.25),
		Stock("Fleep Enterprises", 60, 6.5)
		};

	cout.precision(2);			// #.## format
	cout.setf(ios::fixed, ios::floatfield);		// #.## format
	cout.setf(ios::showpoint);	// #.## format

	cout << "Stock holdings:\n";
	for (int st = 0; st < STKS; st++)
		stocks[st].show();

	Stock top = stocks[0];
	for (st = 1; st < STKS; st++)
		top = top.topval(stocks[st]);
	cout << "\nMost valuable holding:\n";
	top.show();

	return 0;
}



An Abstract Data Type



// stack.h -- class definition for the stack ADT

#ifndef _STACK_H_
#define _STACK_H_
#include "booly.h" // define Bool, False, True
typedef unsigned long Item;

class Stack
{
private:
	enum {MAX = 10};	// constant specific to class
	Item items[MAX];	// holds stack items
	int top;		// index for top stack item
public:
	Stack();
	Bool isempty() const;
	Bool isfull() const;
	// push() returns False if stack already is full, True otherwise
	Bool push(const Item & item);	// add item to stack
	// pop() returns False if stack already is empty, True otherwise
	Bool pop(Item & item);	// pop top into item
};
#endif



// booly.h -- Boolean definitions

// eventually to be replaced by new C++ bool type
#ifndef _BOOLY_H_
#define _BOOLY_H_
enum Bool {False, True}; // False = 0, True = 1
#endif



// stack.h -- class definition for the stack ADT

#ifndef _STACK_H_
#define _STACK_H_
#include "booly.h" // define Bool, False, True
typedef unsigned long Item;

class Stack
{
private:
	enum {MAX = 10};	// constant specific to class
	Item items[MAX];	// holds stack items
	int top;		// index for top stack item
public:
	Stack();
	Bool isempty() const;
	Bool isfull() const;
	// push() returns False if stack already is full, True otherwise
	Bool push(const Item & item);	// add item to stack
	// pop() returns False if stack already is empty, True otherwise
	Bool pop(Item & item);	// pop top into item
};
#endif



// stacker.cpp -- test Stack class

#include <iostream.h>
#include <ctype.h>
#include "stack.h"
int main(void)
{
	Stack st;	// create an empty stack
	char c;
	unsigned long po;
	cout << "Please enter A to add a purchase order,\n"
		 << "P to process a PO, or Q to quit.\n";
	while (cin >> c && toupper(c) != 'Q')
	{
		while (cin.get() != '\n')
			continue;
		if (!isalpha(c))
		{
			cout << '\a';
			continue;
		}
		switch(c)
		{
		case 'A':
		case 'a':	cout << "Enter a PO number to add: ";
				cin >> po;
				if (st.isfull())
					cout << "stack already full\n";
				else
					st.push(po);
				break;
		case 'P':
		case 'p':	if (st.isempty())
					cout << "stack already empty\n";
				else {
					st.pop(po);
					cout << "PO #" << po << " popped\n";
					break;
				}
		}
		cout << "Please enter A to add a purchase order,\n"
			 << "P to process a PO, or Q to quit.\n";
	}
	cout << "Bye\n";
	return 0;
}