Theory:: in Real-Life, Complex Objects Are Often Built From Smaller, Simpler Objects. For Example

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

LAB 08

Summary

Items Description
Course Title Object Oriented Programming

Lab Title Composition

Duration 3 Hours

Operating System Visual Studio / Visual C++


/Tool/Language

Objective(s)  To understand the concept of Has-A relationship.


 To understand the design of a composite class.
 To learn the use of class member initialize syntax.
 To understand the use of ‘this’ pointer

Objectives
 To understand the concept of Has-A relationship.
 To understand the design of a composite class.
 To learn the use of class member initialize syntax.
 To understand the use of ‘this’ pointer
THEORY:
In real-life, complex objects are often built from smaller, simpler objects. For example,

 A car is built using a metal frame, an engine, some tires, a transmission, a


steering wheel, and a large number of other parts.
 A personal computer is built from a CPU, a motherboard, some memory, etc.
This process of building complex objects from simpler ones is called
composition (also known as object composition).

More specifically, composition is used for objects that have a has-a relationship to
each other. A car has-a metal frame, has-an engine, and has-a transmission. A
personal computer has-a CPU, a motherboard, and other components.

So far, all of the classes we have used in our examples have had member variables that
are built-in data types (eg. int, float, char). While this is generally sufficient for designing
and implementing small, simple classes, it quickly becomes burdensome for more
complex classes, especially those built from many sub-parts. In order to facilitate the
building of complex classes from simpler ones, C++ allows us to do object composition
in a very simple way — by using classes as member variables in other classes.

Composition is generally used when you want the features of an existing class inside
your new class, but not its interface. That is, you embed an object to implement features
of your new class, but the user of your new class sees the interface you’ve defined
rather than the interface from the original class. To do this, you follow the typical path of
embedding private objects of existing classes inside your new class.

The following examples illustrates the idea of composition.

Example 7.1

#include <iostream>
using namespace std;

class Engine {
public:
void start() const {}
void rev() const {}
void stop() const {}
};

class Wheel {
public:
void inflate(int psi) const {}
};

class Window {
public:
void rollup() const {}
void rolldown() const {}
};

class Door {
public:
Window window;
void open() const {}
void close() const {}
};

class Car {
public:
Engine engine;
Wheel wheel[4];
Door left, right; // 2-door
};

int main() {
Car car;
car.left.window.rollup();
car.wheel[0].inflate(72);
}
Initializing Class Member Variables

The preferred way to initialize class members is through initializer lists rather than
assignment. This will be illustrated through the following example where we first create
a class Date and then a class Employee with objects of Date as its data members.

Example 7.2

class Date
{public:
Date(int m=1,int d=1,int y=1990);
void print() const;
private:
int month;
int day;
int year;
};
Date::Date(int mn,int dy,int yr)
{
month=mn;
day=dy;
year=yr;
}
void Date::print() const
{cout<<month<<"-"<<day<<"-"<<year<<endl;
}
class Employee
{public:
Employee(int,Date,Date);
void print() const;
private:
int ID;
Date birthDate;
Date hireDate;
};
Employee::Employee(int eID,Date dateOfBirth,Date
dateOfHire):ID(eID),birthDate(dateOfBirth),hireDate(dateOfHire){}
void Employee::print() const
{cout<<"ID="<<ID;
cout<<"Birth day=";
birthDate.print();
cout<<"hire day =";
hireDate.print();
cout<<endl;
}
int main()
{
//Date birth;
Date birth(5,5,1997);
Date hire(1,10,2013);
Employee manager(123,birth,hire);
manager.print();
system("pause");
return 0;
}

The user of class Employee sees the interface:

Employee( int eID, Date dateOfBirth, Date dateOfHire )

Carefully see how the eID and the two dates are initialized using the initializer list rather
than assignments.

mployee::Employee( int eID, Date dateOfBirth, Date dateOfHire )


: ID(eID),birthDate( dateOfBirth ), hireDate( dateOfHire )

The keyword this


The keyword this represents a pointer to the object whose member function is being
executed. It is a pointer to the object itself.

The ‘this’ pointer is a pointer accessible only within the nonstatic member functions of
a class. Consider the following segment of the class Date.

void Date::setMonth( int mn )


{
month = mn; // These three statements
this->month = mn; // are equivalent
(*this).month = mn;
}

In the above example, all the three statements are equivalent. The following example
also illustrates the use of this pointer.

Example 7.3

class MyClass {
int data;
public:
MyClass() {data=100;};
void Print1();
void Print2();
};

// Not using this pointer


void MyClass::Print1() {
cout << data << endl;
}

// Using this pointer


void MyClass::Print2() {
cout << "My address = " << this << endl;
cout << this->data << endl;
}

int main()
{
MyClass a;
a.Print1();
a.Print2();

OUTPUT:
100
My address = 0012FF88
100

‘this’ pointer can also be used to resolve ambiguity.

Example 7.4

#include <iostream>
using namespace std;

class MyClass {
int data;
public:
void SetData(int data);
int GetData() { return data; };
};
// Same name for function argument and class member
// this pointer is used to resolve ambiguity
void MyClass::SetData(int data) {
this->data = data;
}

int main()
{
MyClass a;
a.SetData(100);
cout << a.GetData() << endl;
}
LAB TASKS

TASK #01
Create a class Point with two data members x, y. Provide appropriate constructors,
get, set and display m ethods.

Create a class Triangle with three Points as its data members. Provide appropriate
constructo rs for this class and a display method which calls the display methods of
the three Points.

In the main function, declare three points and pass them to the constructor of the
class Triangle. Call the display method of Triangle to verify th e coordinates of the
triangle.

Print your name, reg,n o, section, semester in main using cout statements.

TASK #02
Create separate header file(s) for the above code for each of the class definition
and separate .cpp file four your main()

You might also like