SlideShare a Scribd company logo
1
1
Video Lecture
What is Inheritance ?
 Inheritance is the process of creating new classes, called derived classes, from
existing or base classes.
 The derived class inherits all the capabilities of the base class but can add more
features into itself.
 Classes can inherit attributes (data members) and methods (member
functions) from other classes.
What is the purpose of Inheritance?
 Specialization: Extending the functionality of an existing class
 Generalization: sharing commonality between two or more classes.
 Improved efficiency and greater robustness
2
Terminology
 Derived class or subclass or child class : A class which inherits some of its
attributes and methods from another class.
 Base class or superclass or parent class : A class from which another class
inherits.
 Ancestor : A class’s ancestors are those from which its own super classes
inherit.
 Descendant : A class’s descendants are those which inherit from its sub
classes.
3
Terminology - A Classification Hierarchy
4
Building
Commercial Public Domestic
Office
block
Factory
Masjid Hospital
Office
block
Apartment
Block
A ‘kind of’
Commercial building
(AKO)
A ‘kind of’ Building
(AKO)
Arrow in diagram
means
’inherits from’
Terminology - A Classification Hierarchy
5
Building
Commercial Public Domestic
Office
block
Factory
Masjid Hospital
Office
block
Apartment
Block
A ‘kind of’
Commercial building
(AKO)
A ‘kind of’ Building
(AKO)
Arrow in diagram
means
’inherits from’
Designing your classification hierarchy:
‘A kind of’ or ‘a part of’ relationship ?
6
Car
Vehicle

A car is ‘a kind of’ vehicle
car class can inherit from
vehicle class
Car
Wheel  A wheel isn’t ‘a kind of’ car.
A wheel is ‘a part of’ a car
Designing your classification hierarchy:
Different classes or different states?
Need to analyze whether differences between objects are dependant on type
(such as a house being different to a factory) or state. (different values of the
class’s attributes)
7
Building
Short Building Tall
Building

short building and tall building
might vary only in the value of
the height attribute - don’t need
separate classes
What do objects inherit ?
8
Line
Attributes:
start position
end position
Methods:
draw
Colored Line
Attributes:
colour
Methods:
set colour
A ‘colored line’ is a kind of line. The colored
line class inherits all the attributes and
methods of
the line class and adds attributes and
methods of its own
An object of the ‘colored line’ class has all
the attributes and methods of the ‘line’ base
class as
well as the attributes and methods added by
the derived class
Generalization
 Sharing commonality between two or more classes
 If we were modelling animals in a zoo would we create a separate class for
each animal type?
 This would duplicate attributes such as legs and methods such as getAge()
 Helpful to place common elements (attributes and methods) in a shared base
class and organize problem into an inheritance hierarchy.
 Sometimes this leads to the
creation of abstract classes which
can’t be instantiated directly.
 concrete classes can be instantiated directly 9
Cow Whale Eagle
Elephant
Cow Whale Eagle
Elephant
Animal
Mammal Bird
Abstract classes
Concrete classes
Example 1: Derived Class and Base Class (1/2)
// inheritance with Counter class
#include <iostream>
using namespace std;
class Counter { // base class
protected: // NOTE: not private
unsigned int count; // count
public:
Counter() : count(0) { } // no-arg constructor
Counter(int c) : count(c) { } // 1-arg constructor
unsigned int get_count() const { // return count
return count;
}
Counter operator ++ () { // incr count (prefix)
return Counter(++count);
}
};
10
Example 1: Derived Class and Base Class (2/2)
class CountDn : public Counter { // derived class
public:
Counter operator -- () { // decr count (prefix)
return Counter(--count);
}
};
int main() {
CountDn c1; // c1 of class CountDn
// CountDn c2(100); // Error
cout << "nc1=" << c1.get_count(); // display c1
++c1; ++c1; ++c1; // increment c1,3 times
cout << "nc1=" << c1.get_count(); // display it
--c1; --c1; // decrement c1, twice
cout << "nc1=" << c1.get_count(); // display it
cout << endl;
system("PAUSE");
return 0;
}
11
Generalization
 CountDn class inherits all the features of the Counter class. CountDn doesn’t
need a constructor or the get_count() or operator++() functions, because these
already exist in Counter.
 The first line of CountDn specifies that it is derived from Counter: class
CountDn : public Counter
 Here we use a single colon, followed by the keyword public and the name of
the base class Counter.
 This sets up the relationship between the classes. This line says that CountDn is
derived from the base class Counter.
12
Generalization in UML Class Diagrams
 In the UML, inheritance is called generalization, because
the parent class is a more general form of the child class.
 The child is more specific version of the parent.
 In figure, the direction of the arrow emphasizes that the
derived class refers to functions and data in the base
class, while the base class has no access to the derived
class.
13
14
Counter C1;
C1.count = 5;
// Error
CountDn C2;
--C2 ; // OK
C2.count = 10; // Error
Example 2: Derived Class Constructors (1/2)
#include <iostream> // constructors in derived class
using namespace std;
class Counter {
protected: // NOTE: not private
unsigned int count; // count
public:
Counter() : count(0) {} // constructor, no args
Counter(int c) : count(c) {} // constructor, one arg
unsigned int get_count() const { // return count
return count;
}
Counter operator ++ () { // increment count (prefix)
return Counter(++count);
}
};
class CountDn : public Counter {
public: CountDn() : Counter() {} // constructor, no args
CountDn(int c) : Counter(c) {} // constructor, 1 arg 15
Example 2: Derived Class Constructors (2/2)
CountDn operator -- () { // decr count (prefix)
return CountDn(--count);
}
};
int main() {
CountDn c1; CountDn c2(100);
cout << "nc1=" << c1.get_count(); // display
cout << "nc2=" << c2.get_count(); // display
++c1; ++c1; ++c1; // increment c1
cout << "nc1=" << c1.get_count(); // display it
--c2; --c2; // decrement c2
cout << "nc2=" << c2.get_count(); // display it
CountDn c3 = --c2; // = calls 1 arg constructor
cout << "nc3=" << c3.get_count(); // display c3
cout << endl;
system("PAUSE"); return 0;
} 16
Example 3: Overriding Member Functions (1/3)
//overloading functions in base & derived classes
#include <iostream>
#include <process.h>
using namespace std;
class Stack
{
protected: // NOTE: can’t be private
enum { MAX = 3 }; // size of stack array
int st[MAX]; // stack: array of integers
int top; // index to top of stack
public:
Stack() { top = -1; } // constructor
void push(int var) { // put number on stack
st[++top] = var;
}
int pop() { // take number off stack
return st[top--];
}
};
17
Example 3: Overriding Member Functions (2/3)
class Stack2 : public Stack {
public:
void push(int var) { // put number on stack
if (top >= MAX - 1) { // error if stack full
cout << "nError: stack is full";
system("PAUSE");
exit(1);
}
Stack::push(var); // call push() in Stack class
}
int pop() { // take number off stack
if (top < 0) // error if stack empty
{
cout << "nError: stack is emptyn";
system("PAUSE");
exit(1);
}
return Stack::pop(); // call pop() in Stack class
}
}; 18
Example 3: Overriding Member Functions (3/3)
int main()
{
Stack2 s1;
s1.push(11); // push some values onto stack
s1.push(22);
s1.push(33);
cout << endl << s1.pop(); // pop some values from stack
cout << endl << s1.pop();
cout << endl << s1.pop();
cout << endl << s1.pop(); // oops, popped one too many...
cout << endl;
system("PAUSE");
return 0;
}
19
Example 4: Inheritance in the English Distance Class (1/3)
// inheritance using English Distances
#include <iostream>
using namespace std;
enum posneg { pos, neg }; // for sign in DistSign
class Distance { // English Distance class
protected: // NOTE: can’t be private
int feet; float inches;
public:
Distance() : feet(0), inches(0.0) { } // no-arg constructor
Distance(int ft, float in) : feet(ft), inches(in) { }
void getdist() { // get length from user
cout << "nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() const // display distance
{
cout << feet << "'-" << inches << '"';
}
};
20
Example 4: Inheritance in the English Distance Class (2/3)
class DistSign : public Distance { // adds sign to Distance
private: posneg sign; // sign is pos or neg
public: // no-arg constructor
DistSign() : Distance() { // call base constructor
sign = pos; // set the sign to +
}
// 2- or 3-arg constructor
DistSign(int ft, float in, posneg sg = pos) : Distance(ft, in) { // call base constructor
sign = sg; // set the sign
}
void getdist() { // get length from user
Distance::getdist(); // call base getdist()
char ch; // get sign from user
cout << "Enter sign (+ or -): "; cin >> ch;
sign = (ch == '+') ? pos : neg;
}
void showdist() const { // display distance
cout << ((sign == pos) ? "(+)" : "(-)"); // show sign
Distance::showdist(); // ft and in
}
}; 21
Example 4: Inheritance in the English Distance Class (3/3)
int main()
{
DistSign alpha; // no-arg constructor
alpha.getdist(); // get alpha from user
DistSign beta(11, 6.25); // 3-arg constructor
DistSign gamma(100, 5.5, neg); // 3-arg constructor
cout << "nalpha = "; alpha.showdist(); // display all distances
cout << "nbeta = "; beta.showdist();
cout << "ngamma = "; gamma.showdist();
cout << endl;
system("PAUSE");
return 0;
}
22
Class Hierarchies (UML Diagram)
23
Example 5: Class Hierarchies ( Employee Database ) (1/4)
// models employee database using inheritance
#include <iostream>
using namespace std;
const int LEN = 80; // maximum length of names
class employee // employee class
{
private:
char name[LEN]; // employee name
unsigned long number; // employee number
public:
void getdata() {
cout << "n Enter last name: "; cin.get(name, LEN); fflush(stdin);
cout << " Enter number: "; cin >> number;
}
void putdata() const {
cout << "n Name: " << name;
cout << "n Number: " << number;
}
};
24
Example 5: Class Hierarchies ( Employee Database ) (2/4)
class manager : private employee { // management class
private:
char title[LEN]; // "vice-president" etc.
double dues; // golf club dues
public:
void getdata() {
employee::getdata();
cout << " Enter title: "; cin.get(title, LEN);
cout << " Enter golf club dues: "; cin >> dues;
}
void putdata() const {
employee::putdata();
cout << "n Title: " << title;
cout << "n Golf club dues: " << dues;
}
};
25
Example 5: Class Hierarchies ( Employee Database ) (3/4)
class scientist : private employee { // scientist class
{
private:
int pubs; // number of publications
public:
void getdata()
{
employee::getdata();
cout << " Enter number of pubs: "; cin >> pubs;
}
void putdata() const
{
employee::putdata();
cout << "n Number of publications: " << pubs;
}
};
class laborer : public employee // laborer class
{ };
26
Example 5: Class Hierarchies ( Employee Database ) (4/4)
int main()
{
manager m1, m2;scientist s1;laborer l1;
cout << endl; // get data for several employees
cout << "nEnter data for manager 1"; m1.getdata();
cout << "nEnter data for manager 2"; m2.getdata();
cout << "nEnter data for scientist 1"; s1.getdata();
cout << "nEnter data for laborer 1"; l1.getdata();
// display data for several employees
cout << "nData on manager 1";m1.putdata();
cout << "nData on manager 2";m2.putdata();
cout << "nData on scientist 1";s1.putdata();
cout << "nData on laborer 1";l1.putdata();
cout << endl;
system("PAUSE");
return 0;
}
27
“Abstract” Base Class
 Notice that we don’t define any objects of the base class employee. We use
this as a general class whose purpose is to act as a base from which other
classes are derived.
 The laborer class operates identically to the employee class, since it contains
no additional data or functions.
 It may seem that the laborer class is unnecessary, but by making it a separate
class we emphasize that all classes are descended from the same source,
employee.
 Also, if in the future we decided to modify the laborer class, we would not
need to change the declaration for employee.
 Classes used only for deriving other classes, as employee is in EMPLOY, are
sometimes loosely called abstract classes, meaning that no actual instances
(objects) of this class are created. 28
Example 6: Access Combinations (1/2)
// tests publicly- and privately-derived classes
#include <iostream>
using namespace std;
class A { // base class
private: int privdataA; // (functions have the same access
protected: int protdataA; // rules as the data shown here)
public: int pubdataA;
};
class B : public A { // publicly-derived class
public:
void funct() {
int a;
a = privdataA; // error: not accessible
a = protdataA; // OK
a = pubdataA; // OK
}
};
29
Example 6: Access Combinations (2/2)
class C : private A { // privately-derived class
public:
void funct() {
int a;
a = privdataA; // error: not accessible
a = protdataA; /* OK */ a = pubdataA; // OK
}
};
int main() {
int a; B objB;
a = objB.privdataA; // error: not accessible
a = objB.protdataA; // error: not accessible
a = objB.pubdataA; // OK (A public to B)
C objC;
a = objC.privdataA; // error: not accessible
a = objC.protdataA; // error: not accessible
a = objC.pubdataA; // error: not accessible (A private to C)
system("PAUSE");
return 0;
} 30
Access Combinations
31
Multi Levels of Inheritance
32
Media
Print News
Social
Facebook Tweeter Instagram Jang Khabrain Ary Geo
Example 7: Multi Levels of Inheritance (1/4)
// multiple levels of inheritance
#include <iostream>
#include <stdio.h> // for fflush()
using namespace std;
const int LEN = 80;
class employee {
private:
char name[LEN];
unsigned long number;
public:
void getdata() {
cout << "n Enter last name: ";
cin.get(name, LEN); fflush(stdin);
cout << " Enter number: ";
cin >> number; fflush(stdin);
}
void putdata() const {
cout << "n Name: " << name;
cout << "n Number: " << number;
}
}; 33
UML Diagram
Example 7: Multi Levels of Inheritance (2/4)
// scientist class
class scientist : public employee {
private:
int pubs; // number of publications
public:
void getdata() {
employee::getdata();
cout << " Enter number of pubs: ";
cin >> pubs;
}
void putdata() const {
employee::putdata();
cout << "n Number of publications: "
<< pubs;
}
};
34
Example 7: Multi Levels of Inheritance (3/4)
// laborer class
class laborer : public employee {
};
// foreman class
class foreman : public laborer {
private:
// percent of quotas met successfully
float quotas;
public:
void getdata() {
laborer::getdata();
cout << " Enter quotas: ";
cin >> quotas;
}
void putdata() const {
laborer::putdata();
cout << "n Quotas: " << quotas;
}
};
35
Example 7: Multi Levels of Inheritance (4/4)
int main() {
laborer l1;
foreman f1;
cout << endl;
cout << "nEnter data for laborer 1";
l1.getdata();
cout << "nEnter data for foreman 1";
f1.getdata();
cout << endl;
cout << "nData on laborer 1";
l1.putdata();
cout << "nData on foreman 1";
f1.putdata();
cout << endl;
system("PAUSE");
return 0;
}
36
Multiple Inheritance (UML Diagram)
 A class can be derived from more than one base class.
 This is called multiple inheritance. Figure shows how
 This looks when a class Copier is derived from base classes
 Scanner and Printer. In programming we write as
class Scanner { // base class Scanner
};
class Printer { // base class Printer
};
class Copier : public Scanner, public Printer {
}; // Copier is derived from Scanner and printer
37
Scanner Printer
Copier
Bowler Batsman
Allrounder
Cricketer
Multiple Inheritance (UML Diagram)
38
Person
string name
int age
Person()
void get_data()
void show_data()
Teaching Assistant
Teaching Assistant()
void get_all_data()
void show_all_data()
Faculty
string course
Faculty()
void get_course()
void show_course()
Student
string program
Faculty()
void get_prog()
void show_prog()
Multiple Inheritance (UML Diagram)
39
Teacher
string subject
Teacher()
void get_all_data()
void show_all_data()
Employee
int id
double salary
Employee()
void get_id()
void show_id()
Person
string name
int age
Person()
void get_data()
void show_data()
Device
string name
Device()
void get_name()
void show_name()
Camera_Phone
Camera_Phone()
Camera
image img
Camera()
void take_photo()
void show_photot()
Phone
long duration
Phone()
void Make_Call()
Member Functions in Multiple Inheritance
class student
{ };
class employee
{ };
class manager :
private employee, private student
{ };
class scientist :
private employee, private student
{ };
class laborer : public employee
{ };
40
Example 8: Member Functions in Multiple Inheritance (1/5)
//multiple inheritance with employees and degrees
#include <iostream>
using namespace std;
const int LEN = 80; // maximum length of names
class student { // educational background
private:
char school[LEN]; // name of school or university
char degree[LEN]; // highest degree earned
public:
void getedu() {
cout << " Enter name of school or university: ";
cin >> school;
cout << " Enter highest degree earned n";
cout << " (Highschool, Bachelor's, Master's, PhD): ";
cin >> degree;
}
void putedu() const {
cout << "n School or university: " << school;
cout << "n Highest degree earned: " << degree;
}
}; 41
Example 8: Member Functions in Multiple Inheritance (2/5)
class employee
{
private:
char name[LEN]; // employee name
unsigned long number; // employee number
public:
void getdata() {
cout << "n Enter last name: "; cin >> name;
cout << " Enter number: "; cin >> number;
}
void putdata() const {
cout << "n Name: " << name;
cout << "n Number: " << number;
}
};
42
Example 8: Member Functions in Multiple Inheritance (3/5)
class manager : private employee, private student {
private:
char title[LEN]; // "vice-president" etc.
double dues; // golf club dues
public:
void getdata() {
employee::getdata();
cout << " Enter title: ";
cin >> title;
cout << " Enter golf club dues: ";
cin >> dues;
student::getedu();
}
void putdata() const {
employee::putdata();
cout << "n Title: " << title;
cout << "n Golf club dues: " << dues;
student::putedu();
}
}; 43
Example 8: Member Functions in Multiple Inheritance (4/5)
class scientist : private employee, private student
{
private:
int pubs; // number of publications
public:
void getdata() {
employee::getdata();
cout << " Enter number of pubs: "; cin >> pubs;
student::getedu();
}
void putdata() const {
employee::putdata();
cout << "n Number of publications: " << pubs;
student::putedu();
}
};
44
Example 8: Member Functions in Multiple Inheritance (5/5)
class laborer : public employee {
};
int main() {
manager m1; scientist s1, s2; laborer l1;
cout << endl;
cout << "nEnter data for manager 1"; // get data for
m1.getdata(); // several employees
cout << "nEnter data for scientist 1"; s1.getdata();
cout << "nEnter data for scientist 2"; s2.getdata();
cout << "nEnter data for laborer 1"; l1.getdata();
cout << "nData on manager 1"; //display data for
m1.putdata(); //several employees
cout << "nData on scientist 1"; s1.putdata();
cout << "nData on scientist 2"; s2.putdata();
cout << "nData on laborer 1"; l1.putdata();
cout << endl;
system("PAUSE"); return 0;
} 45
Example 9: Constructors in Multiple Inheritance (1/4)
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name; int age;
public:
Person():name(""), age(0) {}
Person(string name, int age):name(name), age(age) {}
void getInfo(){
cout << "Enter Name: ";
std::getline(std::cin >> std::ws, name); // Read input and ignore leading whitespaces
cout << "Enter Age: "; cin >> age;
}
void showInfo() const {
cout << "Name: " << name << endl << "Age: " << age << endl;
}
}; 46
Example 9: Constructors in Multiple Inheritance (2/4)
class Employee {
private:
int employeeId; double salary;
public:
Employee():employeeId(0), salary(0.0) {}
Employee(int id, double salary):employeeId(id), salary(salary) {}
void getInfo(){
cout << "Enter Employee ID: "; cin >> employeeId;
cout << "Enter Salary: "; cin >> salary;
}
void showInfo() const {
cout << "Employee ID: " << employeeId << endl
<< "Salary: $" << salary << endl;
}
};
47
Example 9: Constructors in Multiple Inheritance (3/4)
class Teacher : public Person, public Employee {
private:
string subject;
public:
Teacher():Person(), Employee(), subject("") {}
Teacher(const string name, int age, int id, double salary, const string subject)
: Person(name, age), Employee(id, salary), subject(subject) {}
void getInfo(){
Person::getInfo(); Employee::getInfo();
cout << "Enter Subject: ";
std::getline(std::cin >> std::ws, subject); // Read input and ignore leading whitespaces
}
void showInfo() const {
Person::showInfo(); Employee::showInfo();
cout << "Subject: " << subject << endl;
}
};
48
Example 9: Constructors in Multiple Inheritance (4/4)
int main() {
Teacher t1("M. Ibrahim", 35, 101, 900.0, "Mathematics");
t1.showInfo();
Teacher t2;
t2.getInfo();
t2.showInfo();
return 0;
}
49
Teacher
string subject
Teacher()
void get_all_data()
void show_all_data()
Employee
int id
double salary
Employee()
void get_id()
void show_id()
Person
string name
int age
Person()
void get_data()
void show_data()
Ambiguity in Multiple Inheritance
 Two base classes have functions with the same name, while a class derived
from both base classes has no function with this name.
 How do objects of the derived class access the correct base class function?
 The name of the function alone is insufficient, since the compiler can’t figure
out which of the two functions is meant.
 Next program demonstrates this situation.
 Another kind of ambiguity arises if you derive a class from two classes that are
each derived from the same class.
 This creates a diamond-shaped inheritance tree.
 The DIAMOND program shows how this looks
50
Example 10: Ambiguity in Multiple Inheritance
#include <iostream> // demonstrates ambiguity in multiple inheritance
using namespace std;
class A {
public: void show() { cout << "Class An"; }
};
class B {
public: void show() { cout << "Class Bn"; }
};
class C : public A, public B { };
int main() {
C objC; // object of class C
// objC.show(); // ambiguous--will not compile
objC.A::show(); // OK
objC.B::show(); // OK
return 0;
}
51
Ex 11: Ambiguity in diamond-shaped multiple inheritance
//diamond.cpp investigates diamond-shaped multiple inheritance
#include <iostream>
using namespace std;
class A {
public:
void func() {
cout << "Hello World n";
}
};
class B : public A { };
class C : public A { };
class D : public B, public C { };
int main() {
D objD;
objD.func(); // ambiguous: won’t compile
objD.B::func(); // OK
return 0;
} 52
Aggregation: Classes Within Classes
53
Aggregation: Classes Within Classes
 If a class B is derived by inheritance from a class A, we can say that “B is a kind
of A.”
 This is because B has all the characteristics of A, and in addition some of its
own.
 It’s like saying that a car is a kind of vehicle : A car has the characteristics
shared by all vehicles (wheels, seats, and so on) but has some distinctive
characteristics of its own (CNG, EFI, automatic etc).
 For this reason inheritance is often called a “kind of” relationship.
Aggregation is called a “has a” relationship. We say a library has a book or an
invoice has an item line.
 Aggregation is also called a “part-whole” relationship: the book is a part of the
library.
54
Aggregation: Classes Within Classes
 In object-oriented programming, aggregation may occur when one object is an
attribute of another. Here’s a case where an object of class A is an attribute of
class B:
class A { };
class B { A objA; /* define objA as an object of class A */ };
 In the UML, aggregation is considered a special kind of association.
 Sometimes it’s hard to tell when an association is also an aggregation.
 It’s always safe to call a relationship an association, but if class A contains
objects of class B, and is organizationally superior to class B, it’s a good
candidate for aggregation.
 A company might have an aggregation of employees, or a stamp collection
might have an aggregation of stamps.
55
Aggregation: Classes Within Classes
 Aggregation is shown in the same way as association in UML class diagrams,
except that the “whole” end of the association line has an open diamond-
shaped arrowhead.
56
Aggregation: Classes Within Classes
 Let’s rearrange the EMPMULT program to use aggregation instead of
inheritance.
 In EMPMULT the manager and scientist classes are derived from the employee
and student classes using the inheritance relationship.
 In our new program, EMPCONT, the manager and scientist classes contain
instances of the employee and student classes as attributes.
 This aggregation relationship is shown in next figure.
57
Aggregation: Classes Within Classes
58
Figure: UML Class Diagram for EMPCONT.
Using Aggregation in programming
 The following mini program shows these relationships in a different way:
class student { };
class employee { };
class manager {
student stu; // stu is an object of class student
employee emp; // emp is an object of class employee
};
class scientist {
student stu; // stu is an object of class student
employee emp; // emp is an object of class employee
};
class laborer{
employee emp; // emp is an object of class employee
};
59
Example 12: Using Aggregation in the Program (1/6)
// empcont.cpp containership with employees and degrees
#include <iostream>
#include <string>
using namespace std;
class student { // educational background
private:
string school; // name of school or university
string degree; // highest degree earned
public:
void getedu() {
cout << " Enter name of school or university: ";
cin >> school;
cout << " Enter highest degree earned n";
cout << " (Highschool, Bachelor's, Master's, PhD): ";
cin >> degree;
}
void putedu() const {
cout << "n School or university: " << school;
cout << "n Highest degree earned: " << degree;
}
}; 60
Example 12: Using Aggregation in the Program (2/6)
class employee {
private:
string name; // employee name
unsigned long number; // employee number
public:
void getdata() {
cout << "n Enter last name: ";
cin >> name;
cout << " Enter number: ";
cin >> number;
}
void putdata() const {
cout << "n Name: " << name;
cout << "n Number: " << number;
}
};
61
Example 12: Using Aggregation in the Program (3/6)
class manager { // management
private:
string title; // "vice-president" etc.
double dues; // golf club dues
employee emp; // object of class employee
student stu; // object of class student
public:
void getdata() {
emp.getdata();
cout << " Enter title: "; cin >> title;
cout << " Enter golf club dues: "; cin >> dues;
stu.getedu();
}
void putdata() const {
emp.putdata();
cout << "n Title: " << title;
cout << "n Golf club dues: " << dues;
stu.putedu();
}
};
62
Example 12: Using Aggregation in the Program (4/6)
class scientist { // scientist
private:
int pubs; // number of publications
employee emp; // object of class employee
student stu; // object of class student
public:
void getdata() {
emp.getdata();
cout << " Enter number of pubs: ";
cin >> pubs;
stu.getedu();
}
void putdata() const {
emp.putdata();
cout << "n Number of publications: "
<< pubs;
stu.putedu();
}
};
63
Example 12: Using Aggregation in the Program (5/6)
class laborer { // laborer class
private:
employee emp; // object of class employee
public:
void getdata() {
emp.getdata();
}
void putdata() const {
emp.putdata();
}
};
64
Example 12: Using Aggregation in the Program (6/6)
int main() {
manager m1; scientist s1, s2; laborer l1;
cout << endl;
cout << "nEnter data for manager 1"; //get data for
m1.getdata(); //several employees
cout << "nEnter data for scientist 1";
s1.getdata();
cout << "nEnter data for scientist 2";
s2.getdata();
cout << "nEnter data for laborer 1"; l1.getdata();
cout << "nData on manager 1"; // display data for
m1.putdata(); // several employees
cout << "nData on scientist 1";
s1.putdata();
cout << "nData on scientist 2";
s2.putdata();
cout << "nData on laborer 1";
l1.putdata();
cout << endl;
return 0;
} 65
Composition: A Stronger Aggregation
 Composition is a stronger form of aggregation. It has all the characteristics of
aggregation, plus two more:
 The part may belong to only one whole.
 The lifetime of the part is the same as the lifetime of the whole.
 A car is composed of doors (among other things). The doors can’t belong to
some other car, and they are born and die along with the car.
 A room is composed of a floor, ceiling, and walls.
 Aggregation is a “has a” relationship, composition is a “consists of”
relationship.
 In UML diagrams, composition is shown in the same way as aggregation, except
that the diamond-shaped arrowhead is solid instead of open.
66
Composition: A Stronger Aggregation
67
Figure: UML Diagram Showing Composition
Chapter Summary
 A class, called the derived class, can inherit the features of another class, called
the base class.
 The derived class can add other features of its own, so it becomes a specialized
version of the base class.
 Inheritance provides a powerful way to extend the capabilities of existing
classes, and to design programs using hierarchical relationships.
 Accessibility of base class members from derived classes and from objects of
derived classes is an important issue.
 Data or functions in the base class that are prefaced by the keyword protected
can be accessed from derived classes but not by any other objects, including
objects of derived classes.
 Classes may be publicly or privately derived from base classes. Objects of a
publicly derived class can access public
68
Chapter Summary
 A class can be derived from more than one base class. This is called multiple
inheritance. A class can also be contained within another class.
 In the UML, inheritance is called generalization. This relationship is
represented in class diagrams by an open triangle pointing to the base (parent)
class.
 Aggregation is a “has a” or “part-whole” relationship: one class contains
objects of another class.
 Aggregation is represented in UML class diagrams by an open diamond
pointing to the “whole” part of the part-whole pair.
 Composition is a strong form of aggregation. Its arrowhead is solid rather than
open.
69
Chapter Summary
 Inheritance permits the reusability of software: Derived classes can extend the
capabilities of base classes with no need to modify—or even access the source
code of—the base class.
 This leads to new flexibility in the software development process, and to a
wider range of roles for software developers.
70
Assignment # 3
71
Assignment No.3.doc
Assignment No.3.pdf

More Related Content

Similar to Object Oriented Programming using C++: Ch09 Inheritance.pptx

Inheritance
InheritanceInheritance
Inheritance
Burhan Ahmed
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
Muraleedhar Sundararajan
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
Amritsinghmehra
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
Thooyavan Venkatachalam
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
Geeks Anonymes
 
What is new in sulu 2.0
What is new in sulu 2.0What is new in sulu 2.0
What is new in sulu 2.0
danrot
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
Amrit Kaur
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
Yu-Sheng (Yosen) Chen
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
Nipam Medhi
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
Ajit Nayak
 
Unit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docxUnit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docx
R.K.College of engg & Tech
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
1HK19CS090MOHAMMEDSA
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
Karthik Rohan
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
shubhra chauhan
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
heinrich.wendel
 
inheritance in OOPM
inheritance in OOPMinheritance in OOPM
inheritance in OOPM
PKKArc
 

Similar to Object Oriented Programming using C++: Ch09 Inheritance.pptx (20)

Inheritance
InheritanceInheritance
Inheritance
 
inheritance c++
inheritance c++inheritance c++
inheritance c++
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
What is new in sulu 2.0
What is new in sulu 2.0What is new in sulu 2.0
What is new in sulu 2.0
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
OO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual FunctionOO-like C Programming: Struct Inheritance and Virtual Function
OO-like C Programming: Struct Inheritance and Virtual Function
 
Interfaces c#
Interfaces c#Interfaces c#
Interfaces c#
 
Object Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part IIIObject Oriented Programming using C++ Part III
Object Oriented Programming using C++ Part III
 
Unit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docxUnit-3 Practice Programs-5.docx
Unit-3 Practice Programs-5.docx
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
inheritance in OOPM
inheritance in OOPMinheritance in OOPM
inheritance in OOPM
 

More from RashidFaridChishti

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
RashidFaridChishti
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
RashidFaridChishti
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
RashidFaridChishti
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
RashidFaridChishti
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
RashidFaridChishti
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
RashidFaridChishti
 

More from RashidFaridChishti (20)

Lab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docxLab Manual Arduino UNO Microcontrollar.docx
Lab Manual Arduino UNO Microcontrollar.docx
 
Object Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docxObject Oriented Programming OOP Lab Manual.docx
Object Oriented Programming OOP Lab Manual.docx
 
Lab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docxLab Manual Data Structure and Algorithm.docx
Lab Manual Data Structure and Algorithm.docx
 
Data Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptxData Structures and Agorithm: DS 24 Hash Tables.pptx
Data Structures and Agorithm: DS 24 Hash Tables.pptx
 
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptxData Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
Data Structures and Agorithm: DS 22 Analysis of Algorithm.pptx
 
Data Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptxData Structures and Agorithm: DS 21 Graph Theory.pptx
Data Structures and Agorithm: DS 21 Graph Theory.pptx
 
Data Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptxData Structures and Agorithm: DS 20 Merge Sort.pptx
Data Structures and Agorithm: DS 20 Merge Sort.pptx
 
Data Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptxData Structures and Agorithm: DS 18 Heap.pptx
Data Structures and Agorithm: DS 18 Heap.pptx
 
Data Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptxData Structures and Agorithm: DS 17 AVL Tree.pptx
Data Structures and Agorithm: DS 17 AVL Tree.pptx
 
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptxData Structures and Agorithm: DS 16 Huffman Coding.pptx
Data Structures and Agorithm: DS 16 Huffman Coding.pptx
 
Data Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptxData Structures and Agorithm: DS 15 Priority Queue.pptx
Data Structures and Agorithm: DS 15 Priority Queue.pptx
 
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptxData Structures and Agorithm: DS 14 Binary Expression Tree.pptx
Data Structures and Agorithm: DS 14 Binary Expression Tree.pptx
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
Data Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptxData Structures and Agorithm: DS 09 Queue.pptx
Data Structures and Agorithm: DS 09 Queue.pptx
 
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptxData Structures and Agorithm: DS 08 Infix to Postfix.pptx
Data Structures and Agorithm: DS 08 Infix to Postfix.pptx
 
Data Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptxData Structures and Agorithm: DS 06 Stack.pptx
Data Structures and Agorithm: DS 06 Stack.pptx
 
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptxData Structures and Agorithm: DS 05 Doubly Linked List.pptx
Data Structures and Agorithm: DS 05 Doubly Linked List.pptx
 
Data Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptxData Structures and Agorithm: DS 04 Linked List.pptx
Data Structures and Agorithm: DS 04 Linked List.pptx
 
Data Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptxData Structures and Agorithm: DS 02 Array List.pptx
Data Structures and Agorithm: DS 02 Array List.pptx
 
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptxObject Oriented Programming using C++: Ch12 Streams and Files.pptx
Object Oriented Programming using C++: Ch12 Streams and Files.pptx
 

Recently uploaded

一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
nedcocy
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
AjmalKhan50578
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
upoux
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
MadhavJungKarki
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
shadow0702a
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
CVCSOfficial
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
Kamal Acharya
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
Prakhyath Rai
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
bijceesjournal
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
bjmsejournal
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 

Recently uploaded (20)

一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
一比一原版(爱大毕业证书)爱荷华大学毕业证如何办理
 
Welding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdfWelding Metallurgy Ferrous Materials.pdf
Welding Metallurgy Ferrous Materials.pdf
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
一比一原版(uofo毕业证书)美国俄勒冈大学毕业证如何办理
 
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
1FIDIC-CONSTRUCTION-CONTRACT-2ND-ED-2017-RED-BOOK.pdf
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
TIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptxTIME TABLE MANAGEMENT SYSTEM testing.pptx
TIME TABLE MANAGEMENT SYSTEM testing.pptx
 
Gas agency management system project report.pdf
Gas agency management system project report.pdfGas agency management system project report.pdf
Gas agency management system project report.pdf
 
Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...Software Engineering and Project Management - Software Testing + Agile Method...
Software Engineering and Project Management - Software Testing + Agile Method...
 
Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...Rainfall intensity duration frequency curve statistical analysis and modeling...
Rainfall intensity duration frequency curve statistical analysis and modeling...
 
Design and optimization of ion propulsion drone
Design and optimization of ion propulsion droneDesign and optimization of ion propulsion drone
Design and optimization of ion propulsion drone
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 

Object Oriented Programming using C++: Ch09 Inheritance.pptx

  • 2. What is Inheritance ?  Inheritance is the process of creating new classes, called derived classes, from existing or base classes.  The derived class inherits all the capabilities of the base class but can add more features into itself.  Classes can inherit attributes (data members) and methods (member functions) from other classes. What is the purpose of Inheritance?  Specialization: Extending the functionality of an existing class  Generalization: sharing commonality between two or more classes.  Improved efficiency and greater robustness 2
  • 3. Terminology  Derived class or subclass or child class : A class which inherits some of its attributes and methods from another class.  Base class or superclass or parent class : A class from which another class inherits.  Ancestor : A class’s ancestors are those from which its own super classes inherit.  Descendant : A class’s descendants are those which inherit from its sub classes. 3
  • 4. Terminology - A Classification Hierarchy 4 Building Commercial Public Domestic Office block Factory Masjid Hospital Office block Apartment Block A ‘kind of’ Commercial building (AKO) A ‘kind of’ Building (AKO) Arrow in diagram means ’inherits from’
  • 5. Terminology - A Classification Hierarchy 5 Building Commercial Public Domestic Office block Factory Masjid Hospital Office block Apartment Block A ‘kind of’ Commercial building (AKO) A ‘kind of’ Building (AKO) Arrow in diagram means ’inherits from’
  • 6. Designing your classification hierarchy: ‘A kind of’ or ‘a part of’ relationship ? 6 Car Vehicle  A car is ‘a kind of’ vehicle car class can inherit from vehicle class Car Wheel  A wheel isn’t ‘a kind of’ car. A wheel is ‘a part of’ a car
  • 7. Designing your classification hierarchy: Different classes or different states? Need to analyze whether differences between objects are dependant on type (such as a house being different to a factory) or state. (different values of the class’s attributes) 7 Building Short Building Tall Building  short building and tall building might vary only in the value of the height attribute - don’t need separate classes
  • 8. What do objects inherit ? 8 Line Attributes: start position end position Methods: draw Colored Line Attributes: colour Methods: set colour A ‘colored line’ is a kind of line. The colored line class inherits all the attributes and methods of the line class and adds attributes and methods of its own An object of the ‘colored line’ class has all the attributes and methods of the ‘line’ base class as well as the attributes and methods added by the derived class
  • 9. Generalization  Sharing commonality between two or more classes  If we were modelling animals in a zoo would we create a separate class for each animal type?  This would duplicate attributes such as legs and methods such as getAge()  Helpful to place common elements (attributes and methods) in a shared base class and organize problem into an inheritance hierarchy.  Sometimes this leads to the creation of abstract classes which can’t be instantiated directly.  concrete classes can be instantiated directly 9 Cow Whale Eagle Elephant Cow Whale Eagle Elephant Animal Mammal Bird Abstract classes Concrete classes
  • 10. Example 1: Derived Class and Base Class (1/2) // inheritance with Counter class #include <iostream> using namespace std; class Counter { // base class protected: // NOTE: not private unsigned int count; // count public: Counter() : count(0) { } // no-arg constructor Counter(int c) : count(c) { } // 1-arg constructor unsigned int get_count() const { // return count return count; } Counter operator ++ () { // incr count (prefix) return Counter(++count); } }; 10
  • 11. Example 1: Derived Class and Base Class (2/2) class CountDn : public Counter { // derived class public: Counter operator -- () { // decr count (prefix) return Counter(--count); } }; int main() { CountDn c1; // c1 of class CountDn // CountDn c2(100); // Error cout << "nc1=" << c1.get_count(); // display c1 ++c1; ++c1; ++c1; // increment c1,3 times cout << "nc1=" << c1.get_count(); // display it --c1; --c1; // decrement c1, twice cout << "nc1=" << c1.get_count(); // display it cout << endl; system("PAUSE"); return 0; } 11
  • 12. Generalization  CountDn class inherits all the features of the Counter class. CountDn doesn’t need a constructor or the get_count() or operator++() functions, because these already exist in Counter.  The first line of CountDn specifies that it is derived from Counter: class CountDn : public Counter  Here we use a single colon, followed by the keyword public and the name of the base class Counter.  This sets up the relationship between the classes. This line says that CountDn is derived from the base class Counter. 12
  • 13. Generalization in UML Class Diagrams  In the UML, inheritance is called generalization, because the parent class is a more general form of the child class.  The child is more specific version of the parent.  In figure, the direction of the arrow emphasizes that the derived class refers to functions and data in the base class, while the base class has no access to the derived class. 13
  • 14. 14 Counter C1; C1.count = 5; // Error CountDn C2; --C2 ; // OK C2.count = 10; // Error
  • 15. Example 2: Derived Class Constructors (1/2) #include <iostream> // constructors in derived class using namespace std; class Counter { protected: // NOTE: not private unsigned int count; // count public: Counter() : count(0) {} // constructor, no args Counter(int c) : count(c) {} // constructor, one arg unsigned int get_count() const { // return count return count; } Counter operator ++ () { // increment count (prefix) return Counter(++count); } }; class CountDn : public Counter { public: CountDn() : Counter() {} // constructor, no args CountDn(int c) : Counter(c) {} // constructor, 1 arg 15
  • 16. Example 2: Derived Class Constructors (2/2) CountDn operator -- () { // decr count (prefix) return CountDn(--count); } }; int main() { CountDn c1; CountDn c2(100); cout << "nc1=" << c1.get_count(); // display cout << "nc2=" << c2.get_count(); // display ++c1; ++c1; ++c1; // increment c1 cout << "nc1=" << c1.get_count(); // display it --c2; --c2; // decrement c2 cout << "nc2=" << c2.get_count(); // display it CountDn c3 = --c2; // = calls 1 arg constructor cout << "nc3=" << c3.get_count(); // display c3 cout << endl; system("PAUSE"); return 0; } 16
  • 17. Example 3: Overriding Member Functions (1/3) //overloading functions in base & derived classes #include <iostream> #include <process.h> using namespace std; class Stack { protected: // NOTE: can’t be private enum { MAX = 3 }; // size of stack array int st[MAX]; // stack: array of integers int top; // index to top of stack public: Stack() { top = -1; } // constructor void push(int var) { // put number on stack st[++top] = var; } int pop() { // take number off stack return st[top--]; } }; 17
  • 18. Example 3: Overriding Member Functions (2/3) class Stack2 : public Stack { public: void push(int var) { // put number on stack if (top >= MAX - 1) { // error if stack full cout << "nError: stack is full"; system("PAUSE"); exit(1); } Stack::push(var); // call push() in Stack class } int pop() { // take number off stack if (top < 0) // error if stack empty { cout << "nError: stack is emptyn"; system("PAUSE"); exit(1); } return Stack::pop(); // call pop() in Stack class } }; 18
  • 19. Example 3: Overriding Member Functions (3/3) int main() { Stack2 s1; s1.push(11); // push some values onto stack s1.push(22); s1.push(33); cout << endl << s1.pop(); // pop some values from stack cout << endl << s1.pop(); cout << endl << s1.pop(); cout << endl << s1.pop(); // oops, popped one too many... cout << endl; system("PAUSE"); return 0; } 19
  • 20. Example 4: Inheritance in the English Distance Class (1/3) // inheritance using English Distances #include <iostream> using namespace std; enum posneg { pos, neg }; // for sign in DistSign class Distance { // English Distance class protected: // NOTE: can’t be private int feet; float inches; public: Distance() : feet(0), inches(0.0) { } // no-arg constructor Distance(int ft, float in) : feet(ft), inches(in) { } void getdist() { // get length from user cout << "nEnter feet: "; cin >> feet; cout << "Enter inches: "; cin >> inches; } void showdist() const // display distance { cout << feet << "'-" << inches << '"'; } }; 20
  • 21. Example 4: Inheritance in the English Distance Class (2/3) class DistSign : public Distance { // adds sign to Distance private: posneg sign; // sign is pos or neg public: // no-arg constructor DistSign() : Distance() { // call base constructor sign = pos; // set the sign to + } // 2- or 3-arg constructor DistSign(int ft, float in, posneg sg = pos) : Distance(ft, in) { // call base constructor sign = sg; // set the sign } void getdist() { // get length from user Distance::getdist(); // call base getdist() char ch; // get sign from user cout << "Enter sign (+ or -): "; cin >> ch; sign = (ch == '+') ? pos : neg; } void showdist() const { // display distance cout << ((sign == pos) ? "(+)" : "(-)"); // show sign Distance::showdist(); // ft and in } }; 21
  • 22. Example 4: Inheritance in the English Distance Class (3/3) int main() { DistSign alpha; // no-arg constructor alpha.getdist(); // get alpha from user DistSign beta(11, 6.25); // 3-arg constructor DistSign gamma(100, 5.5, neg); // 3-arg constructor cout << "nalpha = "; alpha.showdist(); // display all distances cout << "nbeta = "; beta.showdist(); cout << "ngamma = "; gamma.showdist(); cout << endl; system("PAUSE"); return 0; } 22
  • 23. Class Hierarchies (UML Diagram) 23
  • 24. Example 5: Class Hierarchies ( Employee Database ) (1/4) // models employee database using inheritance #include <iostream> using namespace std; const int LEN = 80; // maximum length of names class employee // employee class { private: char name[LEN]; // employee name unsigned long number; // employee number public: void getdata() { cout << "n Enter last name: "; cin.get(name, LEN); fflush(stdin); cout << " Enter number: "; cin >> number; } void putdata() const { cout << "n Name: " << name; cout << "n Number: " << number; } }; 24
  • 25. Example 5: Class Hierarchies ( Employee Database ) (2/4) class manager : private employee { // management class private: char title[LEN]; // "vice-president" etc. double dues; // golf club dues public: void getdata() { employee::getdata(); cout << " Enter title: "; cin.get(title, LEN); cout << " Enter golf club dues: "; cin >> dues; } void putdata() const { employee::putdata(); cout << "n Title: " << title; cout << "n Golf club dues: " << dues; } }; 25
  • 26. Example 5: Class Hierarchies ( Employee Database ) (3/4) class scientist : private employee { // scientist class { private: int pubs; // number of publications public: void getdata() { employee::getdata(); cout << " Enter number of pubs: "; cin >> pubs; } void putdata() const { employee::putdata(); cout << "n Number of publications: " << pubs; } }; class laborer : public employee // laborer class { }; 26
  • 27. Example 5: Class Hierarchies ( Employee Database ) (4/4) int main() { manager m1, m2;scientist s1;laborer l1; cout << endl; // get data for several employees cout << "nEnter data for manager 1"; m1.getdata(); cout << "nEnter data for manager 2"; m2.getdata(); cout << "nEnter data for scientist 1"; s1.getdata(); cout << "nEnter data for laborer 1"; l1.getdata(); // display data for several employees cout << "nData on manager 1";m1.putdata(); cout << "nData on manager 2";m2.putdata(); cout << "nData on scientist 1";s1.putdata(); cout << "nData on laborer 1";l1.putdata(); cout << endl; system("PAUSE"); return 0; } 27
  • 28. “Abstract” Base Class  Notice that we don’t define any objects of the base class employee. We use this as a general class whose purpose is to act as a base from which other classes are derived.  The laborer class operates identically to the employee class, since it contains no additional data or functions.  It may seem that the laborer class is unnecessary, but by making it a separate class we emphasize that all classes are descended from the same source, employee.  Also, if in the future we decided to modify the laborer class, we would not need to change the declaration for employee.  Classes used only for deriving other classes, as employee is in EMPLOY, are sometimes loosely called abstract classes, meaning that no actual instances (objects) of this class are created. 28
  • 29. Example 6: Access Combinations (1/2) // tests publicly- and privately-derived classes #include <iostream> using namespace std; class A { // base class private: int privdataA; // (functions have the same access protected: int protdataA; // rules as the data shown here) public: int pubdataA; }; class B : public A { // publicly-derived class public: void funct() { int a; a = privdataA; // error: not accessible a = protdataA; // OK a = pubdataA; // OK } }; 29
  • 30. Example 6: Access Combinations (2/2) class C : private A { // privately-derived class public: void funct() { int a; a = privdataA; // error: not accessible a = protdataA; /* OK */ a = pubdataA; // OK } }; int main() { int a; B objB; a = objB.privdataA; // error: not accessible a = objB.protdataA; // error: not accessible a = objB.pubdataA; // OK (A public to B) C objC; a = objC.privdataA; // error: not accessible a = objC.protdataA; // error: not accessible a = objC.pubdataA; // error: not accessible (A private to C) system("PAUSE"); return 0; } 30
  • 32. Multi Levels of Inheritance 32 Media Print News Social Facebook Tweeter Instagram Jang Khabrain Ary Geo
  • 33. Example 7: Multi Levels of Inheritance (1/4) // multiple levels of inheritance #include <iostream> #include <stdio.h> // for fflush() using namespace std; const int LEN = 80; class employee { private: char name[LEN]; unsigned long number; public: void getdata() { cout << "n Enter last name: "; cin.get(name, LEN); fflush(stdin); cout << " Enter number: "; cin >> number; fflush(stdin); } void putdata() const { cout << "n Name: " << name; cout << "n Number: " << number; } }; 33 UML Diagram
  • 34. Example 7: Multi Levels of Inheritance (2/4) // scientist class class scientist : public employee { private: int pubs; // number of publications public: void getdata() { employee::getdata(); cout << " Enter number of pubs: "; cin >> pubs; } void putdata() const { employee::putdata(); cout << "n Number of publications: " << pubs; } }; 34
  • 35. Example 7: Multi Levels of Inheritance (3/4) // laborer class class laborer : public employee { }; // foreman class class foreman : public laborer { private: // percent of quotas met successfully float quotas; public: void getdata() { laborer::getdata(); cout << " Enter quotas: "; cin >> quotas; } void putdata() const { laborer::putdata(); cout << "n Quotas: " << quotas; } }; 35
  • 36. Example 7: Multi Levels of Inheritance (4/4) int main() { laborer l1; foreman f1; cout << endl; cout << "nEnter data for laborer 1"; l1.getdata(); cout << "nEnter data for foreman 1"; f1.getdata(); cout << endl; cout << "nData on laborer 1"; l1.putdata(); cout << "nData on foreman 1"; f1.putdata(); cout << endl; system("PAUSE"); return 0; } 36
  • 37. Multiple Inheritance (UML Diagram)  A class can be derived from more than one base class.  This is called multiple inheritance. Figure shows how  This looks when a class Copier is derived from base classes  Scanner and Printer. In programming we write as class Scanner { // base class Scanner }; class Printer { // base class Printer }; class Copier : public Scanner, public Printer { }; // Copier is derived from Scanner and printer 37 Scanner Printer Copier Bowler Batsman Allrounder Cricketer
  • 38. Multiple Inheritance (UML Diagram) 38 Person string name int age Person() void get_data() void show_data() Teaching Assistant Teaching Assistant() void get_all_data() void show_all_data() Faculty string course Faculty() void get_course() void show_course() Student string program Faculty() void get_prog() void show_prog()
  • 39. Multiple Inheritance (UML Diagram) 39 Teacher string subject Teacher() void get_all_data() void show_all_data() Employee int id double salary Employee() void get_id() void show_id() Person string name int age Person() void get_data() void show_data() Device string name Device() void get_name() void show_name() Camera_Phone Camera_Phone() Camera image img Camera() void take_photo() void show_photot() Phone long duration Phone() void Make_Call()
  • 40. Member Functions in Multiple Inheritance class student { }; class employee { }; class manager : private employee, private student { }; class scientist : private employee, private student { }; class laborer : public employee { }; 40
  • 41. Example 8: Member Functions in Multiple Inheritance (1/5) //multiple inheritance with employees and degrees #include <iostream> using namespace std; const int LEN = 80; // maximum length of names class student { // educational background private: char school[LEN]; // name of school or university char degree[LEN]; // highest degree earned public: void getedu() { cout << " Enter name of school or university: "; cin >> school; cout << " Enter highest degree earned n"; cout << " (Highschool, Bachelor's, Master's, PhD): "; cin >> degree; } void putedu() const { cout << "n School or university: " << school; cout << "n Highest degree earned: " << degree; } }; 41
  • 42. Example 8: Member Functions in Multiple Inheritance (2/5) class employee { private: char name[LEN]; // employee name unsigned long number; // employee number public: void getdata() { cout << "n Enter last name: "; cin >> name; cout << " Enter number: "; cin >> number; } void putdata() const { cout << "n Name: " << name; cout << "n Number: " << number; } }; 42
  • 43. Example 8: Member Functions in Multiple Inheritance (3/5) class manager : private employee, private student { private: char title[LEN]; // "vice-president" etc. double dues; // golf club dues public: void getdata() { employee::getdata(); cout << " Enter title: "; cin >> title; cout << " Enter golf club dues: "; cin >> dues; student::getedu(); } void putdata() const { employee::putdata(); cout << "n Title: " << title; cout << "n Golf club dues: " << dues; student::putedu(); } }; 43
  • 44. Example 8: Member Functions in Multiple Inheritance (4/5) class scientist : private employee, private student { private: int pubs; // number of publications public: void getdata() { employee::getdata(); cout << " Enter number of pubs: "; cin >> pubs; student::getedu(); } void putdata() const { employee::putdata(); cout << "n Number of publications: " << pubs; student::putedu(); } }; 44
  • 45. Example 8: Member Functions in Multiple Inheritance (5/5) class laborer : public employee { }; int main() { manager m1; scientist s1, s2; laborer l1; cout << endl; cout << "nEnter data for manager 1"; // get data for m1.getdata(); // several employees cout << "nEnter data for scientist 1"; s1.getdata(); cout << "nEnter data for scientist 2"; s2.getdata(); cout << "nEnter data for laborer 1"; l1.getdata(); cout << "nData on manager 1"; //display data for m1.putdata(); //several employees cout << "nData on scientist 1"; s1.putdata(); cout << "nData on scientist 2"; s2.putdata(); cout << "nData on laborer 1"; l1.putdata(); cout << endl; system("PAUSE"); return 0; } 45
  • 46. Example 9: Constructors in Multiple Inheritance (1/4) #include <iostream> #include <string> using namespace std; class Person { private: string name; int age; public: Person():name(""), age(0) {} Person(string name, int age):name(name), age(age) {} void getInfo(){ cout << "Enter Name: "; std::getline(std::cin >> std::ws, name); // Read input and ignore leading whitespaces cout << "Enter Age: "; cin >> age; } void showInfo() const { cout << "Name: " << name << endl << "Age: " << age << endl; } }; 46
  • 47. Example 9: Constructors in Multiple Inheritance (2/4) class Employee { private: int employeeId; double salary; public: Employee():employeeId(0), salary(0.0) {} Employee(int id, double salary):employeeId(id), salary(salary) {} void getInfo(){ cout << "Enter Employee ID: "; cin >> employeeId; cout << "Enter Salary: "; cin >> salary; } void showInfo() const { cout << "Employee ID: " << employeeId << endl << "Salary: $" << salary << endl; } }; 47
  • 48. Example 9: Constructors in Multiple Inheritance (3/4) class Teacher : public Person, public Employee { private: string subject; public: Teacher():Person(), Employee(), subject("") {} Teacher(const string name, int age, int id, double salary, const string subject) : Person(name, age), Employee(id, salary), subject(subject) {} void getInfo(){ Person::getInfo(); Employee::getInfo(); cout << "Enter Subject: "; std::getline(std::cin >> std::ws, subject); // Read input and ignore leading whitespaces } void showInfo() const { Person::showInfo(); Employee::showInfo(); cout << "Subject: " << subject << endl; } }; 48
  • 49. Example 9: Constructors in Multiple Inheritance (4/4) int main() { Teacher t1("M. Ibrahim", 35, 101, 900.0, "Mathematics"); t1.showInfo(); Teacher t2; t2.getInfo(); t2.showInfo(); return 0; } 49 Teacher string subject Teacher() void get_all_data() void show_all_data() Employee int id double salary Employee() void get_id() void show_id() Person string name int age Person() void get_data() void show_data()
  • 50. Ambiguity in Multiple Inheritance  Two base classes have functions with the same name, while a class derived from both base classes has no function with this name.  How do objects of the derived class access the correct base class function?  The name of the function alone is insufficient, since the compiler can’t figure out which of the two functions is meant.  Next program demonstrates this situation.  Another kind of ambiguity arises if you derive a class from two classes that are each derived from the same class.  This creates a diamond-shaped inheritance tree.  The DIAMOND program shows how this looks 50
  • 51. Example 10: Ambiguity in Multiple Inheritance #include <iostream> // demonstrates ambiguity in multiple inheritance using namespace std; class A { public: void show() { cout << "Class An"; } }; class B { public: void show() { cout << "Class Bn"; } }; class C : public A, public B { }; int main() { C objC; // object of class C // objC.show(); // ambiguous--will not compile objC.A::show(); // OK objC.B::show(); // OK return 0; } 51
  • 52. Ex 11: Ambiguity in diamond-shaped multiple inheritance //diamond.cpp investigates diamond-shaped multiple inheritance #include <iostream> using namespace std; class A { public: void func() { cout << "Hello World n"; } }; class B : public A { }; class C : public A { }; class D : public B, public C { }; int main() { D objD; objD.func(); // ambiguous: won’t compile objD.B::func(); // OK return 0; } 52
  • 54. Aggregation: Classes Within Classes  If a class B is derived by inheritance from a class A, we can say that “B is a kind of A.”  This is because B has all the characteristics of A, and in addition some of its own.  It’s like saying that a car is a kind of vehicle : A car has the characteristics shared by all vehicles (wheels, seats, and so on) but has some distinctive characteristics of its own (CNG, EFI, automatic etc).  For this reason inheritance is often called a “kind of” relationship. Aggregation is called a “has a” relationship. We say a library has a book or an invoice has an item line.  Aggregation is also called a “part-whole” relationship: the book is a part of the library. 54
  • 55. Aggregation: Classes Within Classes  In object-oriented programming, aggregation may occur when one object is an attribute of another. Here’s a case where an object of class A is an attribute of class B: class A { }; class B { A objA; /* define objA as an object of class A */ };  In the UML, aggregation is considered a special kind of association.  Sometimes it’s hard to tell when an association is also an aggregation.  It’s always safe to call a relationship an association, but if class A contains objects of class B, and is organizationally superior to class B, it’s a good candidate for aggregation.  A company might have an aggregation of employees, or a stamp collection might have an aggregation of stamps. 55
  • 56. Aggregation: Classes Within Classes  Aggregation is shown in the same way as association in UML class diagrams, except that the “whole” end of the association line has an open diamond- shaped arrowhead. 56
  • 57. Aggregation: Classes Within Classes  Let’s rearrange the EMPMULT program to use aggregation instead of inheritance.  In EMPMULT the manager and scientist classes are derived from the employee and student classes using the inheritance relationship.  In our new program, EMPCONT, the manager and scientist classes contain instances of the employee and student classes as attributes.  This aggregation relationship is shown in next figure. 57
  • 58. Aggregation: Classes Within Classes 58 Figure: UML Class Diagram for EMPCONT.
  • 59. Using Aggregation in programming  The following mini program shows these relationships in a different way: class student { }; class employee { }; class manager { student stu; // stu is an object of class student employee emp; // emp is an object of class employee }; class scientist { student stu; // stu is an object of class student employee emp; // emp is an object of class employee }; class laborer{ employee emp; // emp is an object of class employee }; 59
  • 60. Example 12: Using Aggregation in the Program (1/6) // empcont.cpp containership with employees and degrees #include <iostream> #include <string> using namespace std; class student { // educational background private: string school; // name of school or university string degree; // highest degree earned public: void getedu() { cout << " Enter name of school or university: "; cin >> school; cout << " Enter highest degree earned n"; cout << " (Highschool, Bachelor's, Master's, PhD): "; cin >> degree; } void putedu() const { cout << "n School or university: " << school; cout << "n Highest degree earned: " << degree; } }; 60
  • 61. Example 12: Using Aggregation in the Program (2/6) class employee { private: string name; // employee name unsigned long number; // employee number public: void getdata() { cout << "n Enter last name: "; cin >> name; cout << " Enter number: "; cin >> number; } void putdata() const { cout << "n Name: " << name; cout << "n Number: " << number; } }; 61
  • 62. Example 12: Using Aggregation in the Program (3/6) class manager { // management private: string title; // "vice-president" etc. double dues; // golf club dues employee emp; // object of class employee student stu; // object of class student public: void getdata() { emp.getdata(); cout << " Enter title: "; cin >> title; cout << " Enter golf club dues: "; cin >> dues; stu.getedu(); } void putdata() const { emp.putdata(); cout << "n Title: " << title; cout << "n Golf club dues: " << dues; stu.putedu(); } }; 62
  • 63. Example 12: Using Aggregation in the Program (4/6) class scientist { // scientist private: int pubs; // number of publications employee emp; // object of class employee student stu; // object of class student public: void getdata() { emp.getdata(); cout << " Enter number of pubs: "; cin >> pubs; stu.getedu(); } void putdata() const { emp.putdata(); cout << "n Number of publications: " << pubs; stu.putedu(); } }; 63
  • 64. Example 12: Using Aggregation in the Program (5/6) class laborer { // laborer class private: employee emp; // object of class employee public: void getdata() { emp.getdata(); } void putdata() const { emp.putdata(); } }; 64
  • 65. Example 12: Using Aggregation in the Program (6/6) int main() { manager m1; scientist s1, s2; laborer l1; cout << endl; cout << "nEnter data for manager 1"; //get data for m1.getdata(); //several employees cout << "nEnter data for scientist 1"; s1.getdata(); cout << "nEnter data for scientist 2"; s2.getdata(); cout << "nEnter data for laborer 1"; l1.getdata(); cout << "nData on manager 1"; // display data for m1.putdata(); // several employees cout << "nData on scientist 1"; s1.putdata(); cout << "nData on scientist 2"; s2.putdata(); cout << "nData on laborer 1"; l1.putdata(); cout << endl; return 0; } 65
  • 66. Composition: A Stronger Aggregation  Composition is a stronger form of aggregation. It has all the characteristics of aggregation, plus two more:  The part may belong to only one whole.  The lifetime of the part is the same as the lifetime of the whole.  A car is composed of doors (among other things). The doors can’t belong to some other car, and they are born and die along with the car.  A room is composed of a floor, ceiling, and walls.  Aggregation is a “has a” relationship, composition is a “consists of” relationship.  In UML diagrams, composition is shown in the same way as aggregation, except that the diamond-shaped arrowhead is solid instead of open. 66
  • 67. Composition: A Stronger Aggregation 67 Figure: UML Diagram Showing Composition
  • 68. Chapter Summary  A class, called the derived class, can inherit the features of another class, called the base class.  The derived class can add other features of its own, so it becomes a specialized version of the base class.  Inheritance provides a powerful way to extend the capabilities of existing classes, and to design programs using hierarchical relationships.  Accessibility of base class members from derived classes and from objects of derived classes is an important issue.  Data or functions in the base class that are prefaced by the keyword protected can be accessed from derived classes but not by any other objects, including objects of derived classes.  Classes may be publicly or privately derived from base classes. Objects of a publicly derived class can access public 68
  • 69. Chapter Summary  A class can be derived from more than one base class. This is called multiple inheritance. A class can also be contained within another class.  In the UML, inheritance is called generalization. This relationship is represented in class diagrams by an open triangle pointing to the base (parent) class.  Aggregation is a “has a” or “part-whole” relationship: one class contains objects of another class.  Aggregation is represented in UML class diagrams by an open diamond pointing to the “whole” part of the part-whole pair.  Composition is a strong form of aggregation. Its arrowhead is solid rather than open. 69
  • 70. Chapter Summary  Inheritance permits the reusability of software: Derived classes can extend the capabilities of base classes with no need to modify—or even access the source code of—the base class.  This leads to new flexibility in the software development process, and to a wider range of roles for software developers. 70
  • 71. Assignment # 3 71 Assignment No.3.doc Assignment No.3.pdf