Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.

Slides:



Advertisements
Similar presentations
CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Advertisements

Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
Inheritance, Polymorphism, and Virtual Functions
Inheritance and Polymorphism CS351 – Programming Paradigms.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSE 332: C++ Classes From Procedural to Object-oriented Programming Procedural programming –Functions have been the main focus so far Function parameters.
Review of C++ Programming Part II Sheng-Fang Huang.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 4 Inheritance Bernard Chen Spring Objective IS-A relationships and the allowable changes for derived classes The concept of polymorphism.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Polymorphism &Virtual Functions 1. Polymorphism in C++ 2 types ▫Compile time polymorphism  Uses static or early binding  Example: Function and operator.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Inheritance Joe Meehean. Object Oriented Programming Objects state (data) behavior (methods) identity (allocation of memory) Class objects definition.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Programming Languages and Paradigms Object-Oriented Programming.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
C/C++ 3 Yeting Ge. Static variables Static variables is stored in the static storage. Static variable will be initialized once. 29.cpp 21.cpp.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Object-Oriented Programming Chapter Chapter
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
ISBN Object-Oriented Programming Chapter Chapter
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Inheritance ndex.html ndex.htmland “Java.
Object Oriented Programming Elhanan Borenstein Lecture #7.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
 Inheritance  Protected Members  Non-public Inheritance  Virtual Function Implementation  Virtual Destructors  Abstract Base Classes and Interfaces.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
CS 342: C++ Overloading Copyright © 2004 Dept. of Computer Science and Engineering, Washington University Overview of C++ Overloading Overloading occurs.
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
CSE 332: C++ Overloading Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both.
A First Book of C++ Chapter 12 Extending Your Classes.
Chapter 2 Objects and Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CS 3370 – C++ Object-oriented Programming
7. Inheritance and Polymorphism
Andy Wang Object Oriented Programming in C++ COP 3330
Programming with ANSI C ++
Inheritance and Polymorphism
Class A { public : Int x; A()
Object-Oriented Programming
Inheritance & Polymorphism
Inheritance, Polymorphism, and Virtual Functions
Overview of C++ Overloading
Overview of C++ Polymorphism
Lecture 10 Concepts of Programming Languages
SPL – PS4 C++ Advanced OOP.
Presentation transcript:

Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors Abstract Base Classes and Interfaces Inheritance & Polymorphism (aka “Object-Oriented Programming”)

Inheritance (Public) inheritance implements an “is-a” relationship –access of inherited members doesn’t change –private members of a base class are not accessible in derived class methods –public inheritance is the default for struct Think “substitutability” –a derived object should be able to “stand-in” via a base pointer –code sharing is just a side effect Don’t inherit just for code sharing

The base class constructor(s) run(s) first –in declaration order, if multiple inheritance –you pass arguments to base class constructors only through the member initializer list –if the base class has a default constructor, no explicit initializer is necessary Then any member objects are initialized –in declaration order Then the derived class constructor runs Destruction is the reverse of this process Object Initialization The Real Story

#include using namespace std; struct A { A() {cout << "A::A()\n";} ~A() {cout << "A::~A()\n";} }; struct B { B() {cout << "B::B()\n";} ~B() {cout << "B::~B()\n";} }; struct C : A { C() {cout << "C::C()\n";} ~C() {cout << "C::~C()\n";} B b; }; int main() { C c; } A::A() B::B() C::C() C::~C() B::~B() A::~A()

// Using Initializers #include using namespace std; struct A { A(int i) {cout << "A::A(" << i << ")\n";} ~A() {cout << "A::~A()\n";} }; struct B { B(int j) {cout << "B::B(" << j << ")\n";} ~B() {cout << "B::~B()\n";} }; struct C : A { C(int i, int j) : A(i), b(j) { cout << "C::C(" << i << ',' << j << ")\n"; } ~C() {cout << "C::~C()\n";} B b; }; int main() { C c(1,2); }

A::A(1) B::B(2) C::C(1,2) C::~C() B::~B() A::~A()

There is a third access specifier - protected –protected members are accessible through derived objects Idiom: Protected Constructors –Used to make a class abstract –An alternative to using pure virtual functions Protected Members

Non-public Inheritance “Secretly” using an implementation Protected Inheritance –Public members in base sub-objects objects are “downgraded” to protected in derived objects –The base class interface is only exposed to derived classes Private Inheritance –Public and protected members in base sub-objects objects are “downgraded” to private in derived objects –Known as pure “Implementation Inheritance” the interface of the base class is not exposed at all –Similar to composition, without explicit forwarding

Name Hiding “Gotcha” Beware when “overriding” functions in derived classes Example: Hide.cpp

Name Lookup Rules 1. Find a scope for the name –A class constitutes a scope –A derived class scope is “nested” in the base class’s scope 2. Perform overload resolution in that scope –Pick unambiguous “best fit” 3. Check access permission Examples: Lookup1-3.cpp

A Lookup Oddity? Why does the following compile? #include int main() { std::string s = "hello"; std::cout << s; // Calls std::operator<<(ostream&, const string&); // but I didn’t import or specify it. }

Argument-dependent Lookup (ADL) States that when looking for a function, it will search the namespace of the parameter(s) as well Since s is in std, it looks in std for operator<<(ostream&, const string&); A convenience –“Implicit import”, if you will Causes weird problems with templates!

The Goal of OOP To treat all objects as base objects via a pointer-to-base But to have their behavior vary automatically depending on the dynamic type of the object Employee SalariedEmployee etc. Employee SalariedEmployee

Heterogeneous Collections int main() { using namespace std; Employee e("John Hourly",16.50); e.recordTime(52.0); SalariedEmployee e2("Jane Salaried", ); e2.recordTime(1.0); Employee* elist[] = {&e, &e2}; int nemp = sizeof elist / sizeof elist[0]; for (int i = 0; i < nemp; ++i) cout getName() << " gets " computePay() << endl; } John Hourly gets 957 Jane Salaried gets 1125

Function Binding Determines the code that executes for a functions call Static binding occurs at compile time –what we’re used to Dynamic binding occurs at run time –what Java and SmallTalk folks are used to –what we want here –determined by the dynamic type of object pointed to

How Virtual Functions Work vptr name rate timeWorked Employee Employee::computePay() vtbl for Employee vptr salaryGrade SalariedEmployee SalariedEmployee::computePay:: vtbl for SalariedEmployee Each class has a vtbl (pointers to its virtual functions) Each object has a vptr (points to its class’s vtbl)

Advantages of Dynamic Binding Client code can just deal with the base type (e.g., Employee* ) Behavior varies transparently according to an object’s dynamic type Client code remains unchanged when new derived types are created! No “ripple effect” for maintainers

Derived Destructors Recall that base class destructors are called automatically when a derived object dies: struct B { ~B() {std::cout << "~B\n";} }; struct D : B// public by default { ~D() {std::cout << "~D\n";} }; int main() { D d; } ~D ~B

Deleting via a Pointer-to-Base int main() { B* pb = new D; delete pb; } ~B// Oops! Derived part not destoyed!

Virtual Destructors Needed when deleting via a pointer-to-base struct B { virtual ~B() {std::cout << "~B\n";} }; int main() { B* pb = new D; delete pb; } ~D// Fixed! ~B

Destructors can be declared virtual –necessary when a base class pointer or reference refers to a derived class object –if the destructor is not declared virtual, only the base class destructor is called –this may cause a memory leak Rule: Base classes should always have a virtual destructor Rule of Thumb: A class that contains a virtual function should also declare a virtual destructor Virtual Destructors

Abstract Classes Sometimes a base class is just a conceptual entity –a category, or umbrella for related classes –you won’t instantiate any objects of that type Vehicle CarTruckBus

Pure Virtual Functions Abstract classes usually have abstract methods: –“Place holder” member functions to be overridden in derived classes –Don’t need an implementation in the base class The presence of such a pure virtual function makes its class abstract Append “= 0” to the function’s declaration

Explicit Interfaces A grouping of method specifications –Used in COM, CORBA, Java,.NET, good OO design Specified with only pure virtual functions in C++ To implement an interface, simply inherit and provide all member function definitions The client programs to the interface –You can change the implementation transparent to the client Example: Strategy Design Pattern

Implicit Interfaces A set of expected operations –a.k.a. “Duck Typing” If they’re there, things just work If not, compile error Example: STL Sequences –Expected interface: copy constructor assignment operator equality operator Example: STL Container Adaptors

RTTI Runtime Type Identification The typeid operator –Returns a type_info object –Include Not useful for much –Type name For built-in and polymorphic types only