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

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

  • 1.
  • 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 classor 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 - AClassification 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 - AClassification 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 classificationhierarchy: ‘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 classificationhierarchy: 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 objectsinherit ? 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 commonalitybetween 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: DerivedClass 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: DerivedClass 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 classinherits 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 UMLClass 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: DerivedClass 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: DerivedClass 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: OverridingMember 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: OverridingMember 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: OverridingMember 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: Inheritancein 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: Inheritancein 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: Inheritancein 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.
  • 24.
    Example 5: ClassHierarchies ( 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: ClassHierarchies ( 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: ClassHierarchies ( 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: ClassHierarchies ( 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: AccessCombinations (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: AccessCombinations (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
  • 31.
  • 32.
    Multi Levels ofInheritance 32 Media Print News Social Facebook Tweeter Instagram Jang Khabrain Ary Geo
  • 33.
    Example 7: MultiLevels 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: MultiLevels 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: MultiLevels 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: MultiLevels 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 (UMLDiagram)  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 (UMLDiagram) 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 (UMLDiagram) 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 inMultiple 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: MemberFunctions 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: MemberFunctions 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: MemberFunctions 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: MemberFunctions 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: MemberFunctions 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: Constructorsin 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: Constructorsin 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: Constructorsin 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: Constructorsin 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 MultipleInheritance  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: Ambiguityin 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: Ambiguityin 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
  • 53.
  • 54.
    Aggregation: Classes WithinClasses  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 WithinClasses  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 WithinClasses  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 WithinClasses  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 WithinClasses 58 Figure: UML Class Diagram for EMPCONT.
  • 59.
    Using Aggregation inprogramming  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: UsingAggregation 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: UsingAggregation 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: UsingAggregation 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: UsingAggregation 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: UsingAggregation 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: UsingAggregation 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 StrongerAggregation  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 StrongerAggregation 67 Figure: UML Diagram Showing Composition
  • 68.
    Chapter Summary  Aclass, 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  Aclass 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  Inheritancepermits 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 AssignmentNo.3.doc Assignment No.3.pdf