shape3: shape3.cc

/* 
 * First example: shapes
 * OOP and C++
 * Note how the main program calls to draw and area become cleaner
 *
 * RunStuff:: g++ THISFILE
 */

#include <stdio.h>

/*
 * Definition of class Rect
 */
class Rect { //*1 Class definitions
public: //*1
	int x, y, wid, ht; //*1
	void draw(); //*1
	float area(); //*1
};

/*
 * Definition of class Circle
 */
class Circle { //*1
public: //*1
	int x, y, rad; //*1
	void draw(); //*1
	float area(); //*1
};

int main () {
	/*
	 * Data definitions
	 */
	Rect r1, r2; //*2 Instantiate objects
	Circle c1; //*2

	/*
	 * Set the locations of the 3 objects
	 */
	r1.x = 10; r1.y = 10; //*3 Set the data
	r1.wid = 50; r1.ht = 50; //*3

	r2.x = 80; r2.y = 10; //*3
	r2.wid = 10; r2.ht = 100; //*3

	c1.x = 35; c1.y = 90; //*3
	c1.rad = 10; //*3

	/*
	 * "Draw" them
	 */
	r1.draw(); //*4 Call the methods
	r2.draw(); //*4
	c1.draw(); //*4

	/*
	 * Compute and print total area
	 */
	printf ("Total area = %f\n", r1.area() + r2.area() + c1.area()); //*4

	return 0;
}

/*
 * Methods for class Rect
 */

void Rect::draw () { //*5 Procedure definitions
	printf ("Drawing rectangle at %d, %d, %d, %d\n", x, y, wid, ht); //*5
}

float Rect::area () { //*5
	return (float) (wid * ht);
}

/*
 * Methods for class Circle
 */

void Circle::draw () { //*5
	printf ("Drawing circle at %d, %d, radius = %d\n", x, y, rad);
}

float Circle::area () { //*5
	return (float) (rad * rad * 3.14159);
}

[download file]