0% found this document useful (0 votes)
5 views22 pages

Lecture 5

The document discusses object-oriented programming concepts, focusing on aggregation, composition, and inheritance relationships between classes. It provides multiple examples of class structures and their relationships, illustrating how objects can contain other objects (composition) and how derived classes inherit properties from base classes (inheritance). Key points include the types of class relationships (uses-a, has-a, is-a) and the implications of access specifications in inheritance.

Uploaded by

kaya-acarbay8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

Lecture 5

The document discusses object-oriented programming concepts, focusing on aggregation, composition, and inheritance relationships between classes. It provides multiple examples of class structures and their relationships, illustrating how objects can contain other objects (composition) and how derived classes inherit properties from base classes (inheritance). Key points include the types of class relationships (uses-a, has-a, is-a) and the implications of access specifications in inheritance.

Uploaded by

kaya-acarbay8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

AGGREGATION (COMPOSITION)

OBJECT MODEL AND CLASS RELATIONSHIP:


An Object model is a software design technique that uses a collection of objects to represent the items in a
program.
The class relationship is the interactions and connections or associations that classes may have with each
other.
There are three basic relationships:
Uses-a: a class relationship in which an object makes use of another object to accomplish a task.
Has-a (aggregation): a class relationship in which one object (first) contains another object (second) and
the second object is an integral part of the first object.
Is-a (inheritance): a class relationship established when a new (derived) class is created from an existing(
base) class when the new class inherits properties from the base class

COMPOSITION: OBJECT AS MEMBER OF CLASSES

Example1:
//birthday.h
class birthday{
private:
int day;
string month;
int year;
public:
birthday(int d,string m,int y)
{
day=d,
month=m;
year=y;
}
void printbday()
{
cout<<day<<"/"<<month<<"/"<<year<<endl;
}
};

//person.h
#include"birthday.h"
class person{
private:
string name;
birthday bday;
public:
person(string nm,birthday bo):name(nm),bday(bo)
{ }
void printperson()
{
cout<<name<<" was born on ";
bday.printbday();
}
};
//main
#include<iostream>
#include<string>
using namespace std;
#include"person.h"
void main()
{
birthday dateOfBirth(23,"January",1900);
person me("Sebnem",dateOfBirth);
me.printperson();
system("pause");
}
Output:
Sebnem was born on 23/January/1900

Example2- Version 1
//member.h
class member{
private:
string name;
public:
member(string nm)
{
name=nm;
}
void printMember()
{
cout<<"Member name:"<<name;
}
};
//team.h
#include "member.h"
class team{
private:
int teamno;
member member1, member2;
static int counter;
public:
team(member mem1, member mem2):member1(mem1),member2(mem2)
{
teamno=counter;
counter++;
}
void printTeam()
{
cout<<"Team No:"<<teamno<<endl;
member1.printMember(); cout<<endl;
member2.printMember(); cout<<endl;
}
}; int team::counter=18;
//project.h
#include "team.h"
class project{
private:
int pno;
string pname;
team projectteam;
public:
project(int pn,string pnm,team pt):projectteam(pt)
{
pno=pn;
pname=pnm;
}
void printProj()
{
cout<<"Project No and Name:"<<pno<<" "<<pname<<endl;
projectteam.printTeam();
}
};
#include<iostream>
#include<string>
using namespace std;
#include "project.h"
void main()
{
member mem1("Ayse"), mem2("Ali"), mem3("Sebnem"),mem4("Sinan");
team team1(mem1,mem2), team2(mem3,mem4);
project project1(1,"Dormitories",team1), project2(2,"Stock",team2);
project1.printProj();
project2.printProj();
system("pause");
}

Example2- Version 2
//member.h
#include<string>
class member{
private:
string name;
public:
member(string nm)
{
name=nm;
}
void printMember()
{
cout<<"Member name:"<<name;
}
};
//team.h
#include<string>
#include "mem1.h"
class team{
private:
int teamno;
member member1, member2;
static int counter;
public:
team(string memname1, string memname2):member1(memname1),member2(memname2)
{
teamno=counter;
counter++;
}
void printTeam()
{
cout<<"Team No:"<<teamno<<endl;
member1.printMember(); cout<<endl;
member2.printMember(); cout<<endl;
}
}; int team::counter=18;

//project.h
#include<string>
#include "team1.h"
class project{
private:
int pno;
string pname;
team projectteam;
public:
project(int pn, string pnm,string mem1,string mem2):projectteam(mem1,mem2)
{
pno=pn;
pname=pnm;
}
void printProj()
{
cout<<"Project No and Name:"<<pno<<" "<<pname<<endl;
projectteam.printTeam();
}
};

//main
#include<iostream>
#include<string>
using namespace std;
#include"proj1.h"
void main()
{
project project1(1,"Dormitories","Ahmet","Ayse"), project2(2,"Stock","Ramsey","Mary");
project1.printProj();
project2.printProj();
system("pause");
}

Example 3
//date.h
class date
{ int day,month, year;
public:
date(int d=1, int m=1, int y=1600)
{ day=d; month=m; year=y; }

void display()
{ cout<<"\t"<<day<<"/"<<month<<"/"<<year<"\t"; }

void changedate()
{ int last_day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
do{
cout<<"\nEnter new date: " ;
cin>>day>>month>>year;
if(year%4==0&&year%100!=0||year%400==0)
last_day[2]=29;
}while(day>last_day[month]||month>12);
}

void incrementdate()
{
int last_day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(year%4==0&&year%100!=0||year%400==0)
last_day[2]=29;
int n;
cout<<"\nHow many days: ";
cin>>n;
for(int i=0; i<=n;i++)
{ display();
if(month>=12&&day>=31)
{ day=1; month=1; year++;
cout<<"\nhappy new year\n";
}
if(day<last_day[month])
day++;
else if(day>=last_day[month])
{ day=1; month++; }
}
}
};
//student.h
#include"date.h"
class student
{ private:
char name[20];
date bday; //object data member
public:
student()
{
cout<<"Enter student name: ";
cin>>name;
bday.changedate();
}
void printstd()
{ cout<<name<<endl;
bday.display();
cout<<endl;
}
};
//studentbday.cpp
#include<iostream>
using namespace std;
#include"datefrmt.h"
#include"student.h"

void main()
{
student st1[3] ; //array object
cout<<"NAME\tBIRTHDATE\n";
for(int i=0;i<3;i++)
st1[i].printstd();
system("pause");
}

Enter student name: Ahmet

Enter new date: 22 01 1990


Enter student name: Ali

Enter new date: 23 02 1980


Enter student name: Fatma

Enter new date: 15 05 1998


NAME BIRTHDATE
Ahmet 22/1/1990
Ali 23/2/1980
Fatma 15/5/1998

Press any key to continue . . .


Example 4
Office Phone
//phone.h
class phone
{ private:
int areacode, number;
public:
phone(int ac, int no)
{ areacode=ac; number = no; }
print()
{ cout<<"\t"<<"("<<areacode<<")"<<number; }
};
//person.h
class person
{ private:
char name[20];
phone officephone;
public:
person(char* nm, int c, int n): officephone( c,n)
{ strcpy(name,nm); }
print()
{ cout<<"\t"<<name<<"\t";
officephone.print();
}
};
//car.h
class car
{ private:
char plateno[8], color[10];
person owner;
public:
car( char* pno, char* clr,char* nm, int c, int n):owner(nm,c,n)
{ strcpy(plateno,pno);
strcpy(color,clr);
}
print()
{ cout<<plateno<<"\t"<<color;
owner.print();
}
};

//source file
#include <iostream.h>
#include <string.h>
#include"phone.h"
#include"person.h"
#include"car.h"
main()
{ car mycar("FA308","red","Aybar",392,6301135);
cout<<"plateno\tcolor\towner name\toffice phone no\n";
mycar.print();
}
-------------------------------------------------------------------------------------------------------
Output
Plateno color owner name office phone no
FA308 red Aybar (392)6301135

Example 5
Create a tour class with the following attributes and methods:
Each tour has a unique id number that is assigned by the computer.
Each tour has a name, price, start date, end date, origin city, and arrival city.
Each date has a day, month, and year;
Each city has a name and country.
Methods:
Each class's Constructor methods have arguments with a default value.
Tour class has a duration() function which calculates the duration of the tour and returns it to the main.
Each class has a print() function that prints the value of data members to the screen.
Output format:
TOUR
IDNO STARTDATE ENDDATE DURATION ORIJIN CITY ARRIVAL CITY PRICE
999 23/4/2002 26/4/2002 3 DAYS ERC-TRNC IST-TR 180
1000 21/4/2002 30/4/2002 9 DAYS IST-TR NY-USA 2000
INHERITANCE and the IS-A Relationship
When one object is a specialized version of another object, there is an “is-a (inheritance)” relationship
between them.
When an inheritance relationship exists between objects, it means that the specialized object has all of the
characteristics of the general object, plus additional characteristics that make it special. In OOP
programming, inheritance is used to create “is-a” relationship classes. Inheritance involves a base class and
the derived class is the specialized class.
The derived class is based on or derived from, the base class.
You can think of the Base class as the Parent and the Derived class as the Child.

Protected Members:
Protected members of a base class are like private members, except they may be accessed by derived
classes. The base class access specification determines how private, protected, and public base class
members are accessed when they are inherited by the derived class.
Protected members are inaccessible to all other codes in the program.

The derived class inherits the member variables and member functions of the base class without any of
them being rewritten. Furthermore, new member variables and functions may be added to the derived
class to make it more specialized than the base class.

Base Class Access Specifications


How members of the base class appear in the derived class.
Private:  Private members of the base class are inaccessible to the derived class
 Protected members of the base class become private members of the
derived class
 Public members of the base class become private members of the
derived class
Protected:  Private members are inaccessible
 Protected members of the base class become protected members of
the derived class
 Public members of the base class become protected members of the
derived class
Public:  Private members are inaccessible
 Protected members of the base class become protected members of
the derived class
 Public members of the base class become public members of the
derived class

Important Note:
Do not confuse base class specification with member access specification.
Member access specification determines the type of access for members defined in the class, whereas
base access specification determines the type of access for inherited members.
Q1:Are constructors inherited by the derived classes?
Answer: No

Q2:What is the reason?


Answer: Constructors are different from other class methods in that they create new objects, whereas
other methods are invoked by existing objects. This is one reason constructors aren’t inherited.
Inheritance means a derived object can use a base-class method, but, in the case of constructors, the
object doesn’t exist until after the constructor has done its work.

Constructors are:
 generated automatically if you do not write them,
 (all base class constructors are called implicitly even if you don't do it manually.
You do not call them explicitly but by creating objects.

Example:
class checkpoint{
private:
int a;
protected:
int b;
int c;
void setA(int x)
{
a=x;
}
public:
void setB(int y)
{
b=y;
}
void setC(int z)
{
c=z;
}
};
a) class Quiz : private checkpoint
b) class Quiz : protected checkpoint
c) class Quiz : public checkpoint
Indicate whether each member of the “checkpoint” class is private, protected, public or inaccessible.

Why do we use sub-classes?

 Software re-usability
 Save times
 Re-use of debugged software
 Reduce software complexity
Example 1:

We have students in our department. Each student has a number and name. Some of the students are
working as a student assistant. The department pays salaries to assistants according to the following
formula.

Salary = working hour * payment range.

1. Design an inheritance relationship between the student and the assistant student.
2. List all the student number, names, and their salary on the screen.

Student

 Student number
 Name

Assistant student

 Student number
 Name
 Working hours
 Payment range

Inheritance relation between student and assistant student:

STUDENT

ASSISTANT

#include<iostream.h>
class student
{
protected:
long stnumber;
char name[15];
public:
student( )
{ cin>>stnumber>>name; }
long getnumber() { return stnumber; }
char* getname( ) { return name;}
};
class assistant : public student
{
private:
float range, workinghour;
public:
assistant()
{ cout<<stnumber<<"\t"<<name<<"\t"<<"range and working hour: ";
cin>>range>>workinghour; }

float salary( ) { return range*workighour; }


float getrange( ) {return range;}
float gethour(){return workinghour;}
};
main()
{
student st1; assistant st2;
cout<<"number\tname\thour\trange\tsalary\n";
cout<<st1.getnumber()<<"\t"<<st1.getname()<<"\n";
cout<<st1.getnumber()<<"\t"<<st2.getname()<<"\t";
cout<<st2.getrange()<<"\t"<<st2.gethour()<<"\t"<<st2.salary()<<endl;
}

Example 2:

//inhex1.cppinclude <iostream.h>

class base {
protected:
int i, j;
public:
void set(int a, int b) {i=a ; j=b;}
void show() { cout<<i<<" "<<j<<"\n"; }
};
//i and j inherited as protected

class derived1 : public base {


int k;
public:
void setk() {k = i*j; } //legal
void showk() { cout<<k<<"\n";}
};

//i and j inherited indirectly through derived1


class derived2 : public derived1 {
int m;
public:
void setm() {m = i- j ; } //legal
void showm() {cout << m << "\n";}
};

void main()
{
derived1 ob1;
derived2 ob2;

ob1.set(2, 3);
ob1.show();
ob1.setk();
ob1.showk();

ob2.set(3, 4);
ob2.show();
ob2.setk();
ob2.setm();
ob2.showk();
ob2.showm();
getch();
}

/* Output of above program :


2 3
6
3 4
12
-1
*/

Example 3:
//WHEN SHOW() FUNCTION HAS THE SAME NAME IN BASE,DERIVED1, AND
//DERIVED2 CLASSES WE HAVE TO ACTIVATE EACH FUNCTION USING
//THE FOLLOWING TECHNIQUES:

//inhex2.cpp
#include <iostream.h>
class base {
protected:
int i, j;
public:
void set(int a, int b) {i=a ; j=b;}
void show() { cout<<i<<" "<<j<<"\n"; }
};
//i and j inherited as protected

class derived1 : public base {


int k;
public:
void setk() {k = i*j; } //legal
void show() { cout<<k<<"\n";}
};

//i and j inherited indirectly through derived1


class derived2 : public derived1 {
int m;
public:
void setm() {m = i- j ; } //legal
void show() {cout << m << "\n";}
};

void main()
{
derived1 ob1;
derived2 ob2;

ob1.set(2, 3);
ob1.base::show(); //execute base class show() – ob1 is derived1 class object
ob1.setk();
ob1.show(); //execute derived1 class show() – ob1 is derived1 class object

ob2.set(3, 4);
ob2.base::show(); //execute base class show() – ob2 is derived2 class object
ob2.setk();
ob2.setm();
ob2.derived1::show(); //execute derived1 class show() – ob2 is derived2 class object
ob2.show(); //execute derived2 class show() – ob2 is derived2 class object
getch();
}
/* Output of above program :
2 3
6
3 4
12
-1
*/

Example 4:

//inhex3.cpp
#include <iostream.h>
class base1 {
protected:
int x;
public:
void showx() {cout << x << "\n"; }
};
class base2 {
protected:
int y;
public:
void showy() {cout << y <<"\n";}
};

// inherit multiple base classes


class derived : public base1, public base2 {
public:
void set (int i, int j) {x=i ; y=j; }
};

void main()
{
derived ob;
ob.set(10,20);
ob.showx();
ob.showy();
getch();
}

//inhex4.cpp
#include <iostream.h>
class building {
protected:
int rooms, floors,area;
public:
void set_rooms(int r) {rooms=r;}
int get_rooms() {return rooms;}
void set_floors(int f) {floors=f;}
int get_floors() {return floors;}
void set_area(int a) {area=a;}
int get_area() {return area;}
};

//house is derived from building


class house : public building {
private:
int bedrooms,baths;
public:
void set_bedrooms(int b) {bedrooms=b;}
int get_bedrooms() {return bedrooms;}
void set_baths(int b) {baths=b; }
int get_baths() {return baths;}
};
//school is also derived from building
class school : public building {
private:
int classrooms, offices;
public:
void set_classrooms(int c) { classrooms=c; }
int get_classrooms() {return classrooms; }
void set_offices(int of) { offices=of; }
int get_offices() { return offices;}
};

void main()
{

house h;
school s;
h.set_rooms(12);
h.set_floors(3);
h.set_area(4500);
h.set_bedrooms(5);
h.set_baths(3);
cout<<"\nHouse has "<<h.get_bedrooms();
cout<< " bedrooms.";

s.set_rooms(200);
s.set_classrooms(180);
s.set_offices(5);
s.set_area(25000);

cout<<"\nSchool has "<<s.get_classrooms();


cout<<" classrooms.";
cout<<"\nIts area is "<<s.get_area();
getch();
}
/* Output of above program :
House has 5 bedrooms.
School has 180 classrooms.
Its area is 25000
*/

Example 5:

//EXECUTION OF CONSTRUCTORS AND DESTRUCTORS IN INHERITED CLASSES


//inhex5.cpp
#include <iostream.h>
#include <conio.h>
class base {
public:
base() {cout<<"Constructing base\n";}
~base() {cout<<"Destructing base\n";}
};

class derived1 : public base {


public:
derived1() {cout<<"Constructing derived1\n";}
~derived1() {cout<<"Destructing derived1\n";}
};

class derived2 : public derived1 {


public:
derived2() {cout<<"Constructing derived2\n";}
~derived2() {cout<<"Destructing derived2\n";}
};

void main()
{

derived2 ob1;
getch();
}
/* Output of above program :
Constructing base
Constructing derived1
Constructing derived2
Destructing derived2
Destructing derived1
Destructing base
*/

Example 6:

Class Mammal Dog Cat


Data members Age Age Age
Weight Weight Weight
Breed
Methods GetAge() GetAge() GetAge()
SetAge() SetAge() SetAge()
GetWeight() GetWeight() GetWeight()
SetWeight() SetWeight() SetWeight()
Sleep() Sleep() Sleep()
GetBreed() Meow()
SetBreed()
Bark()

Using inheritance design necessary mammal, dog, and cat classes. Note that the following methods should
have the behavior explained below:
-bark() should display “Wouf Wouf!” on the screen
-meow() should display meow..” on the screen
-sleep() should display “go away I am sleeping..” on the screen

class Mammal
{
protected:
int age;
float weight;
public:
int GetAge( ) {return age;}
void SetAge( int t) { age=t;}
float GetWeight( ) { return weight;}
void SetWeight(float w) { weight=w;}
void Sleep() { cout<<”Donot disturb!!”;
};

class Dog:public Mammal


{
private:
char breed[20];
public:
char* GetBreed( ) {return breed;}
void SetBreed(char*);
void Bark() { cout<<”How How!!”;}
};
void Dog::SetBreed(char *newb)
{
strncpy(breed,newb,19);
breed[19]=’\0’;
}
class Cat:public Mammal
{
public:
void Meow() {cout<<”meow meow!!”;}
};

#include <iostream.h>
#include “mammal.h”
void main()
{
dog lassie;
cat boncuk;
lassie.SetAge(2);
lassie.SetWeight(15);
cout << “LASSIE : \n”;
cout<<lassie.GetAge();
cout<<lassie.GetWeight();
boncuk.SetAge(3);
boncuk.SetWeight(15);
lassie.SetBreed(Doberman);
cout<<lassie.GetBreed();
lassie.sleep();
lassie.bark();
cout <<”BONCUK :\n”;
boncuk.sleep();
boncuk.Meow();
boncuk.GetAge();
boncuk.GetWeight();
}
Example 7: ( WITH STATIC CLASS DATA MEMBER)
The following example sets up an inheritance relation between classes employee, SalariedWorker, and
HourlyPaid. It uses a static data member to count all employees covering both SalariedWorker and
HourlyPaid class objects.

Employee

Employee_count(static)
Personnel_id
Name

Employee()
GetID();
GetName()
GetEmployeeCount()

SalariedWorker HourlyPaid

Department_number Factory_section
Annual_salary Hourly_rate

SalariedWorker() HourlyPaid()
GetDepartment() GetSection()
GetSalary() GetRate()
ChangeDepartment() ChangeSection()
ChangeSalary() ChangeRate()

# include "employee.h"
void main()
{
SalariedWorker salaried[2];
HourlyPaid manual[3];
cout<<"Employee count is = "<<employee::getEmployeeCount();
}

//employee.h
#include <iostream.h>
class employee base class
{
protected:
static int employee_count;
int personnel_id;
char name[30];
public:
employee();
int getID();
char* getName();
static int getEmployeeCount();
};
int employee::employee_count; Necessary for static data members

class SalariedWorker : public employee Derived class


{
private:
int department_number;
float annual_salary;
public:
SalariedWorker();
int getDepartment();
float getSalary();
void changeDepartment(int new_dept);
void changeSalary(float new_salary);
};

class HourlyPaid : public employee Derived class


{
private:
char factory_section;
float hourly_rate;
public:
HourlyPaid();
char getSection();
float getRate();
void changeSection(char new_section);
void changeRate(float new_rate);
};
employee :: employee()
{
employee_count++;
personnel_id=employee_count;
cout << "Enter Employee Name ";
cin>> name;
}
int employee :: getID()
{
return personnel_id;
}
char* employee :: getName()
{
return name;
}
int employee :: getEmployeeCount()
{
return employee_count;
}
SalariedWorker :: SalariedWorker()
{
cout << "Enter Annual Salary for " << name ;
cin >> annual_salary;
cout << "\nEnter Department Number ";
cin >> department_number;
}
float SalariedWorker::getSalary()
{ return annual_salary; }

int SalariedWorker :: getDepartment()


{ return department_number; }

void SalariedWorker :: changeSalary(float new_salary)


{ annual_salary = new_salary; }

void SalariedWorker::changeDepartment(int new_dept)


{ department_number = new_dept; }

HourlyPaid :: HourlyPaid()
{
cout << "Enter Hourly Rate for "<<name;
cin >> hourly_rate;
cout << "\nEnter Factory Section ";
cin >> factory_section;
}

char HourlyPaid :: getSection()


{ return factory_section; }

float HourlyPaid::getRate()
{ return hourly_rate; }

void HourlyPaid::changeSection(char new_section)


{ factory_section = new_section; }

void HourlyPaid::changeRate(float new_rate)


{ hourly_rate = new_rate; }

Multiple Inheritance Example


class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b)
{
width=a;
height=b;
}
};

class Output {
public:
void print(int i)
{
cout << i << "\n";
}
};

class Rectangle: public Polygon, public Output {


public:
Rectangle (int a, int b) : Polygon(a,b) {}
int area ()
{ return width*height; }
};

class Triangle: public Polygon, public Output {


public:
Triangle (int a, int b): Polygon(a,b) {}
int area ()
{ return width*height/2; }
};

#include <iostream>
using namespace std;
#include"polygon.h"
#include"output.h"
#include"rectangle.h"
#include"triangle.h"
int main () {
Rectangle rect (4,5);
Triangle trgl (8,6);
rect.print(rect.area());
trgl.print(trgl.area());
system("pause");
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy