11601902 c lecture 06 class part 3
DESCRIPTION
c++TRANSCRIPT
Introduction to Object-OrientedProgramming
Classes 3
Lecture 6Lecture 6
Contents:
Objects and Data TypesObjects within ClassesDynamically Allocation of ObjectsPointers to Class ObjectsArrays of ObjectsArrays of Pointers to ObjectsDynamically Allocation in ClassesAbout StructuresUnionsPointers to Structures
Objects and Data Types
The key thing to remember about objects are simply user-defined data types.
We can declare instances/objects of classes (though with a somewhat new syntax)
MyClass test;MyClass test2(5, 6);
#include <iostream>using namespace std; class Car { public: void drive ( int speed, int distance); void displayData ( ); private: int speed; int distance;};
void Car::drive(int speed_2, int distance_2) { speed = speed_2; distance = distance_2; } void Car:: displayData () { cout<<"The speed of the car is: " << speed<< " km/hour"<<endl; cout<<"The distance traveled by the” <<“car is: " <<distance << " km“ <<endl; }
int main( ) { Car c; c.drive(100, 2000); c.displayData(); system("pause"); return 0; }
#include <iostream>using namespace std;
class CRectangle { int width, height; public: CRectangle (); CRectangle (int,int); int area (void) {return (width*height);}};
CRectangle::CRectangle () { width = 5; height = 5;}
CRectangle::CRectangle (int a, int b) { width = a; height = b;}
int main () { CRectangle rect (3,4); CRectangle rectb; cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; system("pause"); return 0;}
We can have objects as data members of other classes.
class MyClass { … private: MyOtherClass x; // Instance of a class MyOtherClass *y; // Pointer to an instance of // a class };
Objects within Classes
Dynamically Allocation of Objects
Concept: Objects may be created and destroyed while a program is running.
Objects are created “on the fly” while the program is running.
The program can only access the dynamically allocated memory through its address, pointers is required to used those objects.
Dynamic Memory Allocation (Revision)
int *iptr; // create a pointer to an int
iptr = new int; // dynamic allocation of an int
double *dptr; // create a point to a double
dptr = new double[10]; // dynamic allocation of 10 double
delete iptr; // free memory of a single variable
delete [ ] dprt; // free memory of an array
Pointers to Class Objects
When a structure or class object is dynamically created, a pointer must be created to point to the address.
class Circle{ public:
void draw() { … }…
};
Circle *cirPtr; // declares pointer to a class object
cirPtr = new Circle( ); // dynamically allocating of a class object
cirPtr -> draw(); // call draw() with pointer operator
( * cirPtr ) . draw( ); // call draw() with dereferencing the pointer
#include <iostream>using namespace std;
class CRectangle { int width, height; public: void set_values (int, int); int area (void) {return (width * height);}};
void CRectangle::set_values (int a, int b){ width = a; height = b;}
int main () { CRectangle a, *b, *c; CRectangle * d = new CRectangle[2]; b= new CRectangle; c= &a; a.set_values (1,2); b->set_values (3,4); d->set_values (5,6); d[1].set_values (7,8); cout << "a area: " << a.area() << endl; cout << "*b area: " << b->area() << endl; cout << "*c area: " << c->area() << endl; cout << "d[0] area: " << d[0].area() << endl; cout << "d[1] area: " << d[1].area() << endl; system("pause"); return 0;}
#include <iostream>#include <string>using namespace std;
class Cat {public: Cat(string name = "tom", string color = "black_and_white") : _name(name), _color(color) {}
~Cat() {} void setName(string name) {_name = name;} string getName() {return _name;} void setColor(string color) { _color = color; } string getColor() { return _color; } void speak() { cout << "meow" << endl; }private: string _name; string _color;};
int main() { Cat myCats[4] = { Cat("Homer"), Cat("Marge"), Cat("Bart"),Cat("Lisa")};
Cat myOtherCats[3] = { Cat("Chris", "Gray"), Cat("Charles", "White"), Cat("Cindy", "BlueGray") };
Cat *catpt = new Cat[5]; Cat *pt; pt = catpt; for (int i = 0; i < 5; i++) { pt->setName("Felix"); pt->setColor("Black"); pt++; } for (int i = 0; i < 5; i++) { cout << (i+1) << ": " << catpt[i].getName() << endl; } myCats[0].speak(); myCats[1].speak(); delete[] catpt; system("pause"); return 0;}
Arrays of Objects and Arrays of Pointers to Objects
We can create arrays of objects OR array of pointers to objects:
MyClass test[10]; // arrays of objects
MyClass* test2[10]; // arrays of pointers to objectsfor (int i = 0; i < 10; i++) {
test2[i] = new MyClass(i, i + 1); // create the objects}
Dynamic Memory Allocation in ClassesMemory dynamically allocated in a class
constructor should be deleted in the destructor to avoid memory leak.
class A { public: A( ) { // constructor int * iptr = new int[5]; // memory allocation } ~A( ) { // destructor delete [ ] iptr; // memory de-allocation }
};
#include <iostream>using namespace std;
class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area (void) { return (*width * *height); }};
CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b;}CRectangle::~CRectangle () { delete width; delete height;}
int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; system("pause"); return 0;}
Structures
Structures group a set of variables together into a single item.
It can be think of as classes without functions.
struct PayRoll { int empNumber; string name; double hours,
payRate, grossPay;
};
Initialization of Structures
struct Date
{ int day, month, year;
};
Date birthday = { 23, 8, 1983 } ; // ok, initialization list
Date birthday = { 23, 8 } ; // ok, year is not initialized
Date birthday = { 23, , 1983 } ; // illegal initialization
1. Using an Initialization List
Initialization of Structures
2. Using a Constructor
struct Date
{ int day, month, year;
Date( ) // Constructor
{ day = 23;
month = 8;
year = 1983;
}
};
Illegal structure declaration
struct Date
{ int day = 23,
month = 8,
year = 1983;
};
Working with Structuresstruct Time
{ int hours, minutes, seconds;
};
Time t, n;
t.hours = 5;
t.minutes = 20;
t.seconds = 15;
n.hours = 0;
// comparing structure variables
if ( t.hours == n.hours ) return true;
Nested Structures
struct Date
{ int day, month, year;
};
struct Student
{
string name;
int studentID;
Date birthday;
};
Student a;
a.Name = “Steven”;
a.studentID = 001;
a.birthday.day = 10;
a.birthday.month = 6;
a.birthday.year = 1988;
Pointers to Structures
struct PayRoll {int empNumber;
};
PayRoll *employee;employee = new PayRoll;employee -> empNumber = 001;( * employee ) . empNumber = 001;
Unions
A union is like a structure, except all the members occupy the same memory area.
Only one member can be used at a time.
union PaySource{ short hours; float sales;};
PaySource employee;
Discussion:
Design a class for a widget manufacturing plant. Assuming that 10 widgets may be produced each hour, the class object will calculate how many days it will take to produce any number of widgets. (The plant operates two shifts of eight hours each per day.) Write a program that asks the user for the number of widgets that have been ordered and then displays the number of days it will take to produce them.
Input Validation: Do not accept negative values for the number of widgets ordered.
Challenge:
Assuming that a year has 365 days, write a class named
DayOfYear that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month. For example,
Day 2 would be January 2Day 32 would be February 1
The constructor for the class should take as parameter an integer representing the day of the year, and the class should have a member function print() that prints the day in the month-day format. The class should have an integer member variable to represent the day, and should have static member variables of type string to assist in the translation from the integer format to the month-day format.