Templates allow functions and classes to work with different data types. Template classes define generic class definitions that can be used for multiple types, while template functions define generic functions. When a template is instantiated, actual code is generated for the specific types used. Exceptions provide a mechanism to handle runtime errors in C++ and are used by enclosing code that may throw exceptions in a try block and catching specific exceptions in catch blocks.
Inheritance, Polymorphism, and Virtual Functions allows code reuse through inheritance. It establishes a hierarchical relationship between classes where a derived class inherits attributes and behaviors from its base class. Constructors and destructors of base classes are automatically called when objects of derived classes are created or destroyed. Derived classes can pass arguments to base class constructors and multiple inheritance determines the order of constructor calls. Object composition allows classes to contain instances of other classes to reuse their functionality.
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
Templates allow functions and classes to work with different data types. Template classes define generic class definitions that can be used for multiple types, while template functions define generic functions. When a template is instantiated, actual code is generated for the specific types used. Exceptions provide a mechanism to handle runtime errors in C++ and are used by enclosing code that may throw exceptions in a try block and catching specific exceptions in catch blocks.
Inheritance, Polymorphism, and Virtual Functions allows code reuse through inheritance. It establishes a hierarchical relationship between classes where a derived class inherits attributes and behaviors from its base class. Constructors and destructors of base classes are automatically called when objects of derived classes are created or destroyed. Derived classes can pass arguments to base class constructors and multiple inheritance determines the order of constructor calls. Object composition allows classes to contain instances of other classes to reuse their functionality.
Example for Abstract Class and Interface.pdfrajaratna4
This document discusses abstract classes and interfaces in C++. It provides three examples:
1) An abstract Shape class with pure virtual calculateArea() function is implemented by Square and Circle classes. This enforces that derived classes provide an implementation of calculateArea().
2) A Shape interface with pure virtual draw() function is implemented by Rectangle and Circle classes, each providing their own draw() method.
3) Another abstract Shape class with pure virtual getArea() function and width/height properties is implemented by Rectangle and Triangle classes, each providing their own getArea() calculation based on width and height.
1) A base class pointer can point to a derived class object but cannot access the derived class's additional functions without a cast.
2) Declaring a function as virtual in the base class allows it to be overridden in derived classes and called polymorphically through a base class pointer.
3) A pure virtual function is like an abstract function that derived classes must implement. A class with a pure virtual function is an abstract class that cannot be instantiated.
The document discusses 5 object-oriented programming techniques:
1) Avoid calling virtual functions from constructors due to polymorphism issues.
2) Preserve method properties like signatures when overriding to adhere to principles like Liskov substitution.
3) Be aware of initialization order problems between classes and languages.
4) Avoid switch/if-else chains checking types and instead use polymorphism with virtual functions.
5) Be cautious of name hiding between scopes as it reduces readability and can cause defects.
The genetic characters transmitted from parent to offspring, taken collectively.
Something, as a quality, characteristic, or other immaterial possession, received from progenitors or predecessors as if by succession.
↓↓↓↓ Read More:
@ Kindly Follow my Instagram Page to discuss about your mental health problems-
-----> https://instagram.com/mentality_streak?utm_medium=copy_link
@ Appreciate my work:
-----> behance.net/burhanahmed1
Thank-you !
Inheritance allows one class to inherit properties from another class called the base or super class. The new class is called the derived or sub-class. There are different types of inheritance like hierarchical and multi-level inheritance. The visibility of members of the base class depends on whether the inheritance is public, private or protected.
oops(object oriented programing ) is introduced in c++ to enhance the 'c' programming. oops concept includes many important concepts like class,objects,abstraction,encapsulation,inheritance etc.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
The document provides an introduction to object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, polymorphism, constructors, destructors, and exception handling. It defines each concept and provides examples of how it is implemented in C++ code. For instance, it explains that a class is a user-defined data type that holds its own data members and member functions, and provides an example class declaration. It also discusses polymorphism and provides examples demonstrating method overloading and overriding.
This document discusses various usability enhancements introduced in modern C++, including C++11/14/17. It covers topics such as auto type deduction, decltype, nullptr, range-based for loops, uniform initialization, lambda expressions, and more. The enhancements aim to improve code readability, reduce errors and increase developer productivity when programming in C++.
Sulu 2.0 introduces new frontend architecture including components, containers, views, services, and stores. On the backend, adjustments are made to the snippet administration including updating routes and navigation. Schema definitions are also updated to be more flexible and reusable across different content types.
This document discusses inheritance in C++. It defines inheritance and the key terminology used. It describes the different types of inheritance including single, hierarchical, multilevel, multiple and hybrid inheritance. Examples of code are provided for each type. Issues that can arise with multiple inheritance like ambiguities are also covered. In summary, the document provides an overview of inheritance in C++ through definitions, explanations and code examples of the various inheritance techniques.
In this short presentation struct inheritance and virtual member function in pure C are demonstrated. With these fundamental techniques, more advanced design patterns are unlocked.
Interfaces are reference types that define a contract that other classes can implement. Interfaces cannot contain fields or constructors, and all members are implicitly public and abstract. A class can implement multiple interfaces, allowing it to inherit functionality from different sources, while only being able to inherit from one base class. Explicit interface implementation allows a class to implement the same method signature defined in multiple interfaces to avoid name collisions.
Object Oriented Programming using C++ Part IIIAjit Nayak
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
The document provides examples of multilevel inheritance in Java. In multilevel inheritance, a subclass inherits from an intermediate derived class, which itself inherits from a base class. This allows subclasses to inherit properties from all parent classes up the inheritance chain. Three programs are given as examples, demonstrating how subclasses can call constructors and methods of parent classes in the inheritance hierarchy.
The document provides an overview of the Open Verification Methodology (OVM) framework. OVM is a SystemVerilog library that implements object-oriented design patterns to provide base classes for verification components. It includes features for component hierarchy, configuration, phasing, reporting, transaction recording, and interfaces based on the Open System C Initiative Transaction Level Modeling 2.0 standard.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
The document discusses various object-oriented programming concepts in Java like inheritance, polymorphism, abstraction and interfaces. It provides code examples to demonstrate single inheritance, method overriding, abstract classes, interfaces and extending interfaces. Static and final keywords are also explained with examples.
The document provides examples of various Java programming concepts like displaying messages, using control structures like if-else, for loops, methods, constructors, access specifiers, static variables and more. It shows how to write simple Java programs to print messages, integers, use conditional and looping statements. It also explains concepts like default and parameterized constructors, static and non-static methods, different access specifiers and their usage. The examples help learn how different Java features can be used to develop programs with classes, objects and methods.
The document provides an overview of C++ vs C# by Shubhra Chauhan. It discusses the key object-oriented programming concepts like classes, objects, inheritance, polymorphism, and how they are implemented in C++ and C#. It includes code examples to demonstrate class usage and inheritance in both languages. The document also compares some similarities and differences between C++ and C# like support for pointers, preprocessors, structures, and goto statements.
The document discusses the history and architecture of Microsoft's .NET framework and C# programming language. It provides an overview of key .NET concepts like assemblies, application domains, and interoperability. It also summarizes major features of C# like namespaces, control flow, iterators, properties, attributes, delegates and events, LINQ, structs and constructors.
Inheritance allows classes to inherit properties from other classes. There are several types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance. Inheritance provides advantages like reducing memory usage and development time by allowing classes to reuse functionality from base classes. Access control and constructors also play an important role in inheritance. Virtual base classes are used to avoid multiple copies of base class members in derived classes during hybrid inheritance. Abstract classes provide a framework for other classes to inherit from but cannot be instantiated themselves.
The genetic characters transmitted from parent to offspring, taken collectively.
Something, as a quality, characteristic, or other immaterial possession, received from progenitors or predecessors as if by succession.
↓↓↓↓ Read More:
@ Kindly Follow my Instagram Page to discuss about your mental health problems-
-----> https://instagram.com/mentality_streak?utm_medium=copy_link
@ Appreciate my work:
-----> behance.net/burhanahmed1
Thank-you !
Inheritance allows one class to inherit properties from another class called the base or super class. The new class is called the derived or sub-class. There are different types of inheritance like hierarchical and multi-level inheritance. The visibility of members of the base class depends on whether the inheritance is public, private or protected.
oops(object oriented programing ) is introduced in c++ to enhance the 'c' programming. oops concept includes many important concepts like class,objects,abstraction,encapsulation,inheritance etc.
C# is similar to C++ but easier to use, as it does not support pointers, multiple inheritance, header files or global variables. Everything must live within a class or struct. The basic syntax will be familiar to C++ programmers. Key features include properties, interfaces, foreach loops, and delegates for event handling. Properties allow custom getter and setter logic and are preferred over public fields. Delegates provide a type-safe way to link methods, and events build on this to prevent issues with multicast delegates. Generics and assemblies are analogous to C++ templates and deployment units.
The document provides an introduction to object-oriented programming (OOP) concepts in C++ including objects, classes, abstraction, encapsulation, inheritance, polymorphism, constructors, destructors, and exception handling. It defines each concept and provides examples of how it is implemented in C++ code. For instance, it explains that a class is a user-defined data type that holds its own data members and member functions, and provides an example class declaration. It also discusses polymorphism and provides examples demonstrating method overloading and overriding.
This document discusses various usability enhancements introduced in modern C++, including C++11/14/17. It covers topics such as auto type deduction, decltype, nullptr, range-based for loops, uniform initialization, lambda expressions, and more. The enhancements aim to improve code readability, reduce errors and increase developer productivity when programming in C++.
Sulu 2.0 introduces new frontend architecture including components, containers, views, services, and stores. On the backend, adjustments are made to the snippet administration including updating routes and navigation. Schema definitions are also updated to be more flexible and reusable across different content types.
This document discusses inheritance in C++. It defines inheritance and the key terminology used. It describes the different types of inheritance including single, hierarchical, multilevel, multiple and hybrid inheritance. Examples of code are provided for each type. Issues that can arise with multiple inheritance like ambiguities are also covered. In summary, the document provides an overview of inheritance in C++ through definitions, explanations and code examples of the various inheritance techniques.
In this short presentation struct inheritance and virtual member function in pure C are demonstrated. With these fundamental techniques, more advanced design patterns are unlocked.
Interfaces are reference types that define a contract that other classes can implement. Interfaces cannot contain fields or constructors, and all members are implicitly public and abstract. A class can implement multiple interfaces, allowing it to inherit functionality from different sources, while only being able to inherit from one base class. Explicit interface implementation allows a class to implement the same method signature defined in multiple interfaces to avoid name collisions.
Object Oriented Programming using C++ Part IIIAjit Nayak
The document discusses inheritance in object-oriented programming. It defines inheritance as a technique where a new subclass inherits attributes and behaviors from an existing superclass without needing to redefine them. This allows code reuse and reduces development costs. The document provides examples of single inheritance with classes like Employee and Manager, and multi-level inheritance with Student, Test, and Result classes. It also discusses polymorphism through method overriding and different types of inheritance like public, private and protected.
The document provides examples of multilevel inheritance in Java. In multilevel inheritance, a subclass inherits from an intermediate derived class, which itself inherits from a base class. This allows subclasses to inherit properties from all parent classes up the inheritance chain. Three programs are given as examples, demonstrating how subclasses can call constructors and methods of parent classes in the inheritance hierarchy.
The document provides an overview of the Open Verification Methodology (OVM) framework. OVM is a SystemVerilog library that implements object-oriented design patterns to provide base classes for verification components. It includes features for component hierarchy, configuration, phasing, reporting, transaction recording, and interfaces based on the Open System C Initiative Transaction Level Modeling 2.0 standard.
The document provides an overview of object-oriented programming concepts in C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance and polymorphism. It also covers procedural programming in C++ and compares it with OOP. Examples are provided to demonstrate creating classes, objects, functions, constructors and destructors. The document contains information on basic C++ programming concepts needed to understand and implement OOP principles in C++ programs.
The document discusses various object-oriented programming concepts in Java like inheritance, polymorphism, abstraction and interfaces. It provides code examples to demonstrate single inheritance, method overriding, abstract classes, interfaces and extending interfaces. Static and final keywords are also explained with examples.
The document provides examples of various Java programming concepts like displaying messages, using control structures like if-else, for loops, methods, constructors, access specifiers, static variables and more. It shows how to write simple Java programs to print messages, integers, use conditional and looping statements. It also explains concepts like default and parameterized constructors, static and non-static methods, different access specifiers and their usage. The examples help learn how different Java features can be used to develop programs with classes, objects and methods.
The document provides an overview of C++ vs C# by Shubhra Chauhan. It discusses the key object-oriented programming concepts like classes, objects, inheritance, polymorphism, and how they are implemented in C++ and C#. It includes code examples to demonstrate class usage and inheritance in both languages. The document also compares some similarities and differences between C++ and C# like support for pointers, preprocessors, structures, and goto statements.
The document discusses the history and architecture of Microsoft's .NET framework and C# programming language. It provides an overview of key .NET concepts like assemblies, application domains, and interoperability. It also summarizes major features of C# like namespaces, control flow, iterators, properties, attributes, delegates and events, LINQ, structs and constructors.
Inheritance allows classes to inherit properties from other classes. There are several types of inheritance including single, multiple, multilevel, hierarchical, and hybrid inheritance. Inheritance provides advantages like reducing memory usage and development time by allowing classes to reuse functionality from base classes. Access control and constructors also play an important role in inheritance. Virtual base classes are used to avoid multiple copies of base class members in derived classes during hybrid inheritance. Abstract classes provide a framework for other classes to inherit from but cannot be instantiated themselves.
Similar to Object Oriented Programming using C++: Ch09 Inheritance.pptx (20)
Use PyCharm for remote debugging of WSL on a Windo cf5c162d672e4e58b4dde5d797...shadow0702a
This document serves as a comprehensive step-by-step guide on how to effectively use PyCharm for remote debugging of the Windows Subsystem for Linux (WSL) on a local Windows machine. It meticulously outlines several critical steps in the process, starting with the crucial task of enabling permissions, followed by the installation and configuration of WSL.
The guide then proceeds to explain how to set up the SSH service within the WSL environment, an integral part of the process. Alongside this, it also provides detailed instructions on how to modify the inbound rules of the Windows firewall to facilitate the process, ensuring that there are no connectivity issues that could potentially hinder the debugging process.
The document further emphasizes on the importance of checking the connection between the Windows and WSL environments, providing instructions on how to ensure that the connection is optimal and ready for remote debugging.
It also offers an in-depth guide on how to configure the WSL interpreter and files within the PyCharm environment. This is essential for ensuring that the debugging process is set up correctly and that the program can be run effectively within the WSL terminal.
Additionally, the document provides guidance on how to set up breakpoints for debugging, a fundamental aspect of the debugging process which allows the developer to stop the execution of their code at certain points and inspect their program at those stages.
Finally, the document concludes by providing a link to a reference blog. This blog offers additional information and guidance on configuring the remote Python interpreter in PyCharm, providing the reader with a well-rounded understanding of the process.
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...IJECEIAES
Medical image analysis has witnessed significant advancements with deep learning techniques. In the domain of brain tumor segmentation, the ability to
precisely delineate tumor boundaries from magnetic resonance imaging (MRI)
scans holds profound implications for diagnosis. This study presents an ensemble convolutional neural network (CNN) with transfer learning, integrating
the state-of-the-art Deeplabv3+ architecture with the ResNet18 backbone. The
model is rigorously trained and evaluated, exhibiting remarkable performance
metrics, including an impressive global accuracy of 99.286%, a high-class accuracy of 82.191%, a mean intersection over union (IoU) of 79.900%, a weighted
IoU of 98.620%, and a Boundary F1 (BF) score of 83.303%. Notably, a detailed comparative analysis with existing methods showcases the superiority of
our proposed model. These findings underscore the model’s competence in precise brain tumor localization, underscoring its potential to revolutionize medical
image analysis and enhance healthcare outcomes. This research paves the way
for future exploration and optimization of advanced CNN models in medical
imaging, emphasizing addressing false positives and resource efficiency.
Gas agency management system project report.pdfKamal Acharya
The project entitled "Gas Agency" is done to make the manual process easier by making it a computerized system for billing and maintaining stock. The Gas Agencies get the order request through phone calls or by personal from their customers and deliver the gas cylinders to their address based on their demand and previous delivery date. This process is made computerized and the customer's name, address and stock details are stored in a database. Based on this the billing for a customer is made simple and easier, since a customer order for gas can be accepted only after completing a certain period from the previous delivery. This can be calculated and billed easily through this. There are two types of delivery like domestic purpose use delivery and commercial purpose use delivery. The bill rate and capacity differs for both. This can be easily maintained and charged accordingly.
Software Engineering and Project Management - Software Testing + Agile Method...Prakhyath Rai
Software Testing: A Strategic Approach to Software Testing, Strategic Issues, Test Strategies for Conventional Software, Test Strategies for Object -Oriented Software, Validation Testing, System Testing, The Art of Debugging.
Agile Methodology: Before Agile – Waterfall, Agile Development.
Rainfall intensity duration frequency curve statistical analysis and modeling...bijceesjournal
Using data from 41 years in Patna’ India’ the study’s goal is to analyze the trends of how often it rains on a weekly, seasonal, and annual basis (1981−2020). First, utilizing the intensity-duration-frequency (IDF) curve and the relationship by statistically analyzing rainfall’ the historical rainfall data set for Patna’ India’ during a 41 year period (1981−2020), was evaluated for its quality. Changes in the hydrologic cycle as a result of increased greenhouse gas emissions are expected to induce variations in the intensity, length, and frequency of precipitation events. One strategy to lessen vulnerability is to quantify probable changes and adapt to them. Techniques such as log-normal, normal, and Gumbel are used (EV-I). Distributions were created with durations of 1, 2, 3, 6, and 24 h and return times of 2, 5, 10, 25, and 100 years. There were also mathematical correlations discovered between rainfall and recurrence interval.
Findings: Based on findings, the Gumbel approach produced the highest intensity values, whereas the other approaches produced values that were close to each other. The data indicates that 461.9 mm of rain fell during the monsoon season’s 301st week. However, it was found that the 29th week had the greatest average rainfall, 92.6 mm. With 952.6 mm on average, the monsoon season saw the highest rainfall. Calculations revealed that the yearly rainfall averaged 1171.1 mm. Using Weibull’s method, the study was subsequently expanded to examine rainfall distribution at different recurrence intervals of 2, 5, 10, and 25 years. Rainfall and recurrence interval mathematical correlations were also developed. Further regression analysis revealed that short wave irrigation, wind direction, wind speed, pressure, relative humidity, and temperature all had a substantial influence on rainfall.
Originality and value: The results of the rainfall IDF curves can provide useful information to policymakers in making appropriate decisions in managing and minimizing floods in the study area.
Design and optimization of ion propulsion dronebjmsejournal
Electric propulsion technology is widely used in many kinds of vehicles in recent years, and aircrafts are no exception. Technically, UAVs are electrically propelled but tend to produce a significant amount of noise and vibrations. Ion propulsion technology for drones is a potential solution to this problem. Ion propulsion technology is proven to be feasible in the earth’s atmosphere. The study presented in this article shows the design of EHD thrusters and power supply for ion propulsion drones along with performance optimization of high-voltage power supply for endurance in earth’s atmosphere.
Null Bangalore | Pentesters Approach to AWS IAMDivyanshu
#Abstract:
- Learn more about the real-world methods for auditing AWS IAM (Identity and Access Management) as a pentester. So let us proceed with a brief discussion of IAM as well as some typical misconfigurations and their potential exploits in order to reinforce the understanding of IAM security best practices.
- Gain actionable insights into AWS IAM policies and roles, using hands on approach.
#Prerequisites:
- Basic understanding of AWS services and architecture
- Familiarity with cloud security concepts
- Experience using the AWS Management Console or AWS CLI.
- For hands on lab create account on [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
# Scenario Covered:
- Basics of IAM in AWS
- Implementing IAM Policies with Least Privilege to Manage S3 Bucket
- Objective: Create an S3 bucket with least privilege IAM policy and validate access.
- Steps:
- Create S3 bucket.
- Attach least privilege policy to IAM user.
- Validate access.
- Exploiting IAM PassRole Misconfiguration
-Allows a user to pass a specific IAM role to an AWS service (ec2), typically used for service access delegation. Then exploit PassRole Misconfiguration granting unauthorized access to sensitive resources.
- Objective: Demonstrate how a PassRole misconfiguration can grant unauthorized access.
- Steps:
- Allow user to pass IAM role to EC2.
- Exploit misconfiguration for unauthorized access.
- Access sensitive resources.
- Exploiting IAM AssumeRole Misconfiguration with Overly Permissive Role
- An overly permissive IAM role configuration can lead to privilege escalation by creating a role with administrative privileges and allow a user to assume this role.
- Objective: Show how overly permissive IAM roles can lead to privilege escalation.
- Steps:
- Create role with administrative privileges.
- Allow user to assume the role.
- Perform administrative actions.
- Differentiation between PassRole vs AssumeRole
Try at [killercoda.com](https://killercoda.com/cloudsecurity-scenario/)
Introduction- e - waste – definition - sources of e-waste– hazardous substances in e-waste - effects of e-waste on environment and human health- need for e-waste management– e-waste handling rules - waste minimization techniques for managing e-waste – recycling of e-waste - disposal treatment methods of e- waste – mechanism of extraction of precious metal from leaching solution-global Scenario of E-waste – E-waste in India- case studies.
AI for Legal Research with applications, toolsmahaffeycheryld
AI applications in legal research include rapid document analysis, case law review, and statute interpretation. AI-powered tools can sift through vast legal databases to find relevant precedents and citations, enhancing research accuracy and speed. They assist in legal writing by drafting and proofreading documents. Predictive analytics help foresee case outcomes based on historical data, aiding in strategic decision-making. AI also automates routine tasks like contract review and due diligence, freeing up lawyers to focus on complex legal issues. These applications make legal research more efficient, cost-effective, and accessible.
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
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
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
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
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
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