Lecture 5
Lecture 5
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");
}
//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.
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
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.
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.
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
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; }
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
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();
}
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
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";}
};
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;}
};
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);
Example 5:
void main()
{
derived2 ob1;
getch();
}
/* Output of above program :
Constructing base
Constructing derived1
Constructing derived2
Destructing derived2
Destructing derived1
Destructing base
*/
Example 6:
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!!”;
};
#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
HourlyPaid :: HourlyPaid()
{
cout << "Enter Hourly Rate for "<<name;
cin >> hourly_rate;
cout << "\nEnter Factory Section ";
cin >> factory_section;
}
float HourlyPaid::getRate()
{ return hourly_rate; }
class Output {
public:
void print(int i)
{
cout << i << "\n";
}
};
#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;
}