Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September.

Slides:



Advertisements
Similar presentations
Constructors: Access Considerations DerivedClass::DerivedClass( int iR, float fVar) : BaseClass(fVar) { m_uiRating = uiR; } Alternatively DerivedClass::DerivedClass(
Advertisements

Inheritance. Many objects have a hierarchical relationship –Examples: zoo, car/vehicle, card game, airline reservation system Inheritance allows software.
Inheritance Writing and using Classes effectively.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.
OOP Etgar 2008 – Recitation 61 Object Oriented Programming Etgar 2008 Recitation 6.
OOP Spring 2007 – Recitation 41 Object Oriented Programming Spring 2007 Recitation 4.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
CS 1110 Final Exam: Review Session 2 Part 1 : Inheriting classes 1. Inheritance Facts 2. Constructors in Subclasses BREAK : 10 sec. Part 2 : Working with.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
LECTURE 07 Programming using C# Inheritance
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
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.
Inheritance in C++ CS-1030 Dr. Mark L. Hornick.
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
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
Generalization/Specialization Inheritance & OO Design C++ & OO Programming.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Copyright  Hannu Laine C++-programming Part 3 Hannu Laine.
Multiple Inheritance Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
OOP, Virtual Functions and Inheritance
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Operator Overloading Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Reusing Code in C++ Has-a relationship Classes with member objects(containment) The valarray template class Private & protected inheritance Multiple inheritance.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Virtual FunctionstMyn1 Virtual Functions A virtual function is declared in a base class by using the keyword virtual. A function that you declare as virtual.
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.
Chapter -6 Polymorphism
Inheritance Initialization & Destruction of Derived Objects Protected Members Non-public Inheritance Virtual Function Implementation Virtual Destructors.
Inheritance 2 Mehdi Einali Advanced Programming in Java 1.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Overview of C++ Polymorphism
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Object Oriented Programming in C++ Chapter 7 Dynamic Binding.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Class Inheritance Inheritance as an is-a relationship Public derive one class from another Protected access Initializer lists in constructor Upcasting.
1 Inheritance and Polymorphism Chapter Getting Started Continue the Cat Management example from previous presentation.
CSC 143N 1 CSC 143 Object-Oriented Programming [Chapter 8]
 Virtual Function Concepts: Abstract Classes & Pure Virtual Functions, Virtual Base classes, Friend functions, Static Functions, Assignment & copy initialization,
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
CMSC 202 Polymorphism.
CS 3370 – C++ Object-oriented Programming
7. Inheritance and Polymorphism
Constructor & Destructor
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Polymorphism Polymorphism
Pointers Dr. Bhargavi Goswami Department of Computer Science
Polymorphism CMSC 202, Version 4/02.
Inheritance: Polymorphism and Virtual Functions
Inheritance Virtual Functions, Dynamic Binding, and Polymorphism
Overview of C++ Polymorphism
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Computer Science II for Majors
Presentation transcript:

Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September

What is Inheritance? Inheritance enables classes to inherit attributes and methods from other classes. It allows the sharing of common elements between classes without having to repeat definitions for each class. Inheritance occurs between classes NOT Objects!

Derived & Base Classes (1) A class does not contain state values – it only defines the methods and attributes which may be used in a class. State values are contained in individual objects. A derived class inherits the attributes and methods of a base class. We may build on the derived class by adding attributes and methods.

Derived & Base Classes (2) Base class: a class form which another class inherits. Base classes don’t have to represent anything concrete which could be instantiated as an object of its own. Derived class objects do not inherit any state values from base class objects. The derived class may be extended without effecting the original class..

public inheritance Person Student Every student is a person, but not every person is a student. C++ compiler enforces this!

Typical design Person Student Staff virtual void print()=0; void print(); Person * p = new Student(“Hank”); p->print();

Passing parameters to base class constructor class Person { public: Person(const string & n) : name(n) {} private: string name; }; class Student : public Person{ public: Student(const string & n, float g) : Person(n), gpa(g) {} private: float gpa; };

Typical uses of inheritance Single inheritance – one base class attributes that describe all classes go in the base class attributes that are “special” go in derived class

Easy to extend Can add a new derived class, extending the framework, without changing any existing code: extensibility

is-a doesn’t always work right! fact: birds can fly fact: a penguin is a bird Bird Penguin class Bird { virtual void fly() = 0; }; class Penguin : public Bird { }; What’s wrong with this?

C++ Syntax for Inheritance  : denotes inheritance( also called specialisation or derivation or extension)  public derivations and private derivations are possible.  The protected keyword allows derived classes to access inherited attributes.

Public or Private Derivations? Public derivations: Allow objects of a derived class access to the public section of the base class. Private derivations: Allow a derived object to use the methods defined in the derived class, not those inherited from the base class.

class intObj{ private: int val; public: intObj(){val =0;} int getint() const {return val;} void setint(int x){val = x;} void print(){cout <<val<<endl;} }; class SubintObj: public intObj{ //... } int main(){ intObj obj; obj.print(); SubintObj Sobj; Sobj.print(); } Public Inheritance in C++ The common syntax is: derive SubintObj as a subclass of intObj it is public because it means that the public members of the base class become public members of the derived class. Question: what can we do with the derived class?

class intObj{ protected: int val; public: intObj(){val =0;} int getint() const {return val;} void setint(int x){val = x;} void print(){cout <<val<<endl;} }; class SubintObj: public intObj{ public: void inc(){val++;} }; int main(){ SubintObj Sobj; Sobj.print(); Sobj.inc();Sobj.print(); } Public Inheritance in C++: add a method protected : to allow access This will print out 0 1

class intObj{ private:int val; public: intObj(){val =0;} int getint() const {return val;} void setint(int x){val = x;} void print(){cout <<val<<endl;} }; class SubintObj: public intObj{ public: int count; SubintObj(){count =0;} }; int main(){ SubintObj Sobj; Sobj.print(); cout << Sobj.count; } Public Inheritance in C++: add a data member Question: how can we make sure that the added data type gets initialised correctly when an object of the derived class is constructed? Answer: we write a constructor for the derived class (in this case a default constructor with no parameters). The output is now: 0 Question: how did val get initialised on the previous slide??

Parameters? A derived class will always inherit the constructor of a base class, as well as having its own. The base class constructor is always called first, followed by the constructor of the derived class, and so on down the tree. If the base constructor takes no parameters inheritance is implicit. If it takes parameters these must be stated explicitly in each derived class.

An Example: #include class customer { private: std::string name; public: { customer(std::string name_in) {name = name_in;} }

Inheriting the constructor. class accountcustomer:public customer {private: int account_number; public: accountcustomer(std::string name_in); }; accountcustomer::accountcustomer(std::string name_in):customer(name_in) {// constructor body }

// SubintObj.cc #include class intObj{ private:int val; public: intObj(){val =0;} int getint() const {return val;} void setint(int x){val = x;} void print(){cout <<"intObj:"<<val<<endl;} }; class SubintObj: public intObj{ public: void print(){cout <<"SubintObj:"<<getint()<<endl;} }; int main(){ intObj *obj = new intObj; obj->print(); SubintObj *Sobj = new SubintObj; Sobj->print();} virtual functions & polymorphism This will produce the output: intObj:0 SubintObj:0 The print functions are polymorphic because they work on different types (classes) We have already seen polymorphic functions in the same class, where they have different parameter types

Why use virtual functions place the burden of knowing/choosing the object type on the compiler compiler constructs a vtbl for each class w/ virtual function one table per class; each class has ptr to vtbl vtbl holds pointers to all virtual functions vptrs init in constructor each virtual function is invoked thru its vptr

Do virtual functions have performance penalty? vptr must be init in constructor virtual function is invoked via pointer indirection cannot inline virtual functions more later…

RULE: Never redefine an inherited non-virtual function class Person { public: string getName() const { return name; } private: string name; }; class Student : public Person {}; Student stu; Person * p = &stu; Student * s = &stu; p->getName(); s->getName();

Never redefine an inherited non-virtual function class Person { public: string getName() { return name; } private: string name; }; class Student : public Person { string getName(); }; Student stu; Person * p = &stu; Student * s = &stu; p->getName(); s->getName(); Non-virtual functions are statically bound; virtual functions are dynamically bound

Dynamic binding: virtual functions and polymorphism when the class of the object being pointed at is used (at run time) to decide which method gets executed (its own method) it is dynamic because pointers can be used to point at any subclass object So, for example, if we define a Pets class with 2 subclasses (dog and cat). Each offers a method makenoise(). If we declare an object, Pugsy say, to be a Pet (or a pointer to a pet), then Pugsy may bark or purr depending on whether it is a dog or a cat. The key is that we cannot tell at compile time whether Pugsy is a dog or a cat so the correct method can only be decided at run time Unless we want the Pet method makenoise every time (which we usually do not) then we need some mechanism to tell the compiler to bind the method at run time. This mechanism is a virtual function in C++.

virtual functions and polymorphism class intObj{ private:int val; public: intObj(){val =10;} int getint() const {return val;} void setint(int x){val = x;} void virtual print(){cout <<"intObj:"<<val<<endl;} }; class SubintObj: public intObj{ public: SubintObj(){setint(20);} void print(){cout <<"SubintObj:"<<getint()<<endl;} }; int main(){ intObj obj; SubintObj Sobj; intObj* objPt; objPt = &Sobj; objPt->print(); objPt =&obj; objPt->print(); } The output is: SubintObj:20 intObj:10 So, in this case we have the ‘correct’ method used at run time

Pets and virtual functions example.

// Pets.cc #include class Pet{ public: string name; Pet(){name = "pet";} void print(){cout <<"The Pet is called "<< name<<endl;} }; class Dog: public Pet{ public: Dog(){name = "dog";} void print(){cout <<"The Dog is called "<<name<<endl;} }; class Cat: public Pet{ public: Cat(){name = "cat";} void print(){cout <<"The Cat is called "<<name<<endl;} }; int main(){ Pet p;p.print(); Dog d;d.print(); Cat c;c.print(); } Pets: Cats and Dogs The Pet is called pet The Dog is called dog The Cat is called cat

class Pet{ public: void virtual makenoise(){cout << "pet says " <<endl;} }; class Dog: public Pet{ public: void makenoise(){cout << "dog says woof" <<endl;} }; class Cat: public Pet{ public: void makenoise(){cout << "cat says meaow" <<endl;} }; int main(){ Pet *p1, *p2; Cat c; Dog d; p1 =&c; p2 =& d; p1->makenoise();p2->makenoise(); } Back to Pets, Cats and Dogs Output: cat says meaow dog says woof virtual pointers to objects Pet DogCat