11601902 C Lecture 06 Class Part 3

  • Uploaded by: booksofpavan
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 11601902 C Lecture 06 Class Part 3 as PDF for free.

More details

  • Words: 1,385
  • Pages: 23
Introduction to Object-Oriented Programming Classes 3

Lecture 6

Contents: Objects and Data Types Objects within Classes Dynamically Allocation of Objects Pointers to Class Objects Arrays of Objects Arrays of Pointers to Objects Dynamically Allocation in Classes About Structures Unions Pointers 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 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: " <
int main( ) { Car c; c.drive(100, 2000); c.displayData(); system("pause"); return 0; }

#include 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; }

Objects within Classes We can have objects as data members of other classes. class MyClass { … private: MyOtherClass MyOtherClass };

x; *y;

// Instance of a class // Pointer to an instance of // a class

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; iptr = new int; double *dptr; dptr = new double[10]; delete iptr; delete [ ] dprt;

// create a pointer to an int // dynamic allocation of an int // create a point to a double // dynamic allocation of 10 double // free memory of a single variable // 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 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 #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 objects for (int i = 0; i < 10; i++) { test2[i] = new MyClass(i, i + 1); // create the objects }

Dynamic Memory Allocation in Classes Memory 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 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 1. Using an Initialization List 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

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 Structures struct 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; };

Student a; a.Name = “Steven”;

struct Student { string name; int studentID; Date birthday; };

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 2 Day 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.

Related Documents

Class Lecture # 3
November 2019 17
C-programming-class 3
May 2020 10
06 (part 3)
November 2019 12
Lecture 5 2006 Part 3
November 2019 8
C++lecture
May 2020 13

More Documents from "Jenny Rose G. Sison"