Вы находитесь на странице: 1из 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 <iostream> int main( )
using namespace std; {
class Car { Car c;
public:
void drive ( int speed, int distance); c.drive(100, 2000);
void displayData ( ); c.displayData();
private:
int speed; system("pause");
int distance; return 0;
}; }

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;
}
#include <iostream> int main () {
using namespace std; CRectangle rect (3,4);
CRectangle rectb;
class CRectangle { cout << "rect area: " << rect.area()
int width, height; << endl;
public: cout << "rectb area: " << rectb.area()
CRectangle (); << endl;
CRectangle (int,int); system("pause");
int area (void) {return (width*height);} return 0;
}; }

CRectangle::CRectangle () {
width = 5;
height = 5;
}

CRectangle::CRectangle (int a, int b) {


width = a;
height = b;
}
Objects within Classes
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
};
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> int main () {
using namespace std; CRectangle a, *b, *c;
CRectangle * d = new CRectangle[2];
class CRectangle { b= new CRectangle;
int width, height; c= &a;
public: a.set_values (1,2);
void set_values (int, int); b->set_values (3,4);
int area (void) {return (width * height);} d->set_values (5,6);
}; d[1].set_values (7,8);
cout << "a area: " << a.area()
void CRectangle::set_values (int a, int b) << endl;
{ cout << "*b area: " << b->area()
width = a; << endl;
height = b; 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> int main() {
#include <string> Cat myCats[4] = { Cat("Homer"),
using namespace std; Cat("Marge"), Cat("Bart"),Cat("Lisa")};

class Cat { Cat myOtherCats[3] = {


public: Cat("Chris", "Gray"),
Cat(string name = "tom", string color = Cat("Charles", "White"),
"black_and_white") : _name(name), Cat("Cindy", "BlueGray")
_color(color) {} };

~Cat() {} Cat *catpt = new Cat[5];


void setName(string name) {_name = Cat *pt;
name;} pt = catpt;
string getName() {return _name;} for (int i = 0; i < 5; i++) {
void setColor(string color) { pt->setName("Felix");
_color = color; pt->setColor("Black");
} pt++;
string getColor() { return _color; } }
void speak() { cout << "meow" << endl; for (int i = 0; i < 5; i++) {
} cout << (i+1) << ": " << catpt[i].getName()
private: << endl;
string _name; }
string _color; 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 <iostream> int main () {
using namespace std; CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area()
class CRectangle { << endl;
int *width, *height; cout << "rectb area: " << rectb.area()
public: << endl;
CRectangle (int,int); system("pause");
~CRectangle (); return 0;
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;
}
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
Illegal structure declaration
{ int day, month, year;

struct Date
Date( ) // Constructor
{ int day = 23,
{ day = 23;
month = 8,
month = 8;
year = 1983;
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
a.studentID = 001;
{
string name; a.birthday.day = 10;
int studentID; a.birthday.month = 6;
Date birthday; 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.

Вам также может понравиться