CSIS 123A Lecture 10 Inheritance. Organizing Code Why should programs be organized? –Humans are "complexity challenged" Need simplicity, clarity, efficiency.

Slides:



Advertisements
Similar presentations
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Advertisements

You gotta be cool. Inheritance Base Classes and Derived Classes Inheritance: Public, Protected, Private What is inherited from the base class? Multiple.
Before Introducing Inheritance … Here is another way to re-use what have been developed: This is known as the object composition! A real-world example.
© Copyright Eliyahu Brutman Programming Techniques Course Version 1.0.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Dynamic Memory for Class #include #ifndef STRCLASS_H_ #define STRCLASS_H_ class strclass { private: char *str; int len; static int num_strings; public:
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
OOP Languages: Java vs C++
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract 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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Looking toward C++ Object-Oriented Programming Traditional Programming Procedure-Oriented Programming Task-Based Programming circle method draw data C.draw()
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
C++ Classes CSci 588: Data Structures, Algorithms and Software Design All material not from online sources copyright © Travis Desell, 2011
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Overloading Binary Operators Two ways to overload –As a member function of a class –As a friend function As member functions –General syntax Data Structures.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
C++ Review (3) Structs, Classes, Data Abstraction.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Inheritance. Lecture contents Inheritance Class hierarchy Types of Inheritance Derived and Base classes derived class constructors protected access identifier.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
Object Oriented Programming (OOP) Lecture No. 8. Review ► Class  Concept  Definition ► Data members ► Member Functions ► Access specifier.
CSC241 Object-Oriented Programming (OOP) Lecture No. 4.
Object-Oriented Programming in C++ More examples of Association.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Object-Oriented Programming Chapter Chapter
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
ISBN Object-Oriented Programming Chapter Chapter
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Chapter 9. Inheritance - Basics Inheritance is a mechanism that allows you to base a new class upon the definition of a pre-existing class Subclass inherits.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
1 CSC241: Object Oriented Programming Lecture No 17.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Destructors The destructor fulfills the opposite functionality. It is automatically called when an object.
Classes - Part II (revisited) n Constant objects and member functions n Definition Form of Member Functions n friend functions and friend classes n Constructors.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Classes: Defining Your Own Data Types Basic principles in OOP Define a new data type as a class and use objects of a class Member Functions –Constructors.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
A First Book of C++ Chapter 12 Extending Your Classes.
Abstract classes only used as base class from which other classes can be inherit cannot be used to instantiate any objects are incomplete Classes that.
1 Ugly Realities The Dark Side of C++ Chapter 12.
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Abstract Data Types Programmer-created data types that specify
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Review: Two Programming Paradigms
Introduction to Classes
Chapter 5 Classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
More about OOP and ADTs Classes
Introduction to Classes
More about OOP and ADTs Classes
CS410 – Software Engineering Lecture #5: C++ Basics III
Presentation transcript:

CSIS 123A Lecture 10 Inheritance

Organizing Code Why should programs be organized? –Humans are "complexity challenged" Need simplicity, clarity, efficiency –Solve larger problems –Reduce errors in programs –Programs last longer than expected Major expense is not development but maintenance Includes expansion and bug-fixing

Traditional Organization First breakthrough: Functional Decomposition –Groups of related statements packaged together –Called procedures, functions, subroutines –Organized hierarchically using "flow of control"

Traditional Problems No provision for bundling data with operations –Development of structures and ADTs Access to data through accessor functions Information hiding –Development of OOP and classes Methods and fields bundled together Encapsulation controls access to internal data How are such programs organized?

OOP Organization I Method 1: Communities –Objects offer and request services –Called a USES relationship –Sometimes called a client-server organization –Can be close to traditional organization if you have a "boss" object that controls all others

OOP Organization II Method 2: Composition –Objects are "composed" of other objects –A tighter relationship than Uses

OOP Organization III What is classification? –First step in traditional organization is dividing problem into procedures –First step in OOP is grouping “related” objects together--"finding" classes –How are objects related? –If they have the same attributes and behavior Problem: Providing student refreshments Solution: Cafeteria, Coffee,Candy,Soda Machines

OOP Organization IV What is generalization? –Generalization is a method for organizing classes discovered during classification –Discovering common traits in different classes –Consider those classes “related” Extract common behavior and data into new classes –Similar to refining functions in traditional programs Redundant operations are moved into their own procedures.

OOP Organization V Example: Feeding students –Common behavior of Coffee, Candy, and Soda machines can be combined in new classes

Base class and derived class The ISA Relationship –Relationship between classes –One class is a subset of another –The subset is called a subclass –The superset is called the superclass Subclass normally represents specialization –Contains all attributes and methods of superclass These are called inherited methods (and fields) –Usually adds additional methods or fields

Base class and derived class II

Implementing a derived class Class derivedClass : public baseClass { /* New attributes and methods here */ } –Each class can be directly derived from two classes This is called multiple inheritance Classes can have two immediate ancestor class –Not recommended, best to have a single level of inheritance »Java, C#, etc –Derived class inherits all parent methods and attributes Everything a baseClass can do, a derivedClass object can do Called "the principle of substitutability"

Shape Classes class Polygon { protected: int width, height; public: void set_values (int a, int b){ width=a; height=b;} }; class Rectangle: public Polygon { public: int area () { return (width * height); } }; class Triangle: public Polygon { public: int area () { return (width * height / 2); } };

main int main () { Rectangle rect; Triangle trgl; rect.set_values (4,5); //Notice that set_values is in the base class trgl.set_values (4,5); cout << rect.area() << endl; cout << trgl.area() << endl; return 0; }

Access Specifiers Public –Everyone has access Private –Only members of the same class have access Protected: –Similar to private Only difference occurs with inheritance –Derived class can access the protected members inherited from the base class, but not its private members.

Inheritance access specifiers class CRectangle: public CPolygon –Public keyword after the colon denotes maximum access level for all classes inherited (Cpolygon) Public is most accessible method –The derived class will inherit all the members from the base class. Maintaining their access levels Protected –All public members in base are inherited as protected in derived class Private –All public members in base are inherited as private in derived class

Call Base Class Constructor first If objects of base class need to be initialized, it is up to you to call base class constructor first –Most distant parent constructor called first –Most distant parent destructor called last

class mother { public: mother () { cout << "mother: no parameters\n"; } mother (int a) { cout << "mother: int parameter\n"; } }; class son : public mother { public: son (int a) ; }; son::son(int a) :mother(a); { cout << “ son int paramater\n\n”; }

Intro To Copy Constructors Used to copy an object to a newly created object. Typically looks like the following: –Class_name(const class_name &); Takes a constant reference to a class object as its argument

When A Copy Constructor is Used Whenever a new object is created and initialized to an existing object of the same kind. –Happens in several ways but most typical is: Explicitly initializing a new object to an existing object StringBad motto; StringBad ditto(motto); // All call StringBad(const StringBad &) StringBad motto = motto; StringBad also = StringBad(motto); StringBad * pStringBad = new StringBad(motto);

More Copy Constructor Compiler uses copy constructor whenever a program generates a copy of an object –When a function passes an object by value Or when a function returns an object –Remember passing by value means creating and passing a copy of the original value.

Stringbad.h class StringBad { private: char * str; int len; static int num_strings; //holds number of objects public: StringBad(const char *s); StringBad(); ~StringBad(); friend std::ostream & operator << (std::ostream &os, const StringBad &st); };

What a copy constructor does Default constructor performs a member by member copy of the nonstatic member –Memberwise copying Aka shallow copy. Each member is copied by value. StringBad sports; StringBad sailor = sports; sailor.str = sports.str; sailor.len = sports.len If the member class is an object Copy constructor copies one member object to another Static members are unaffected Belong to the class as a whole not individual objects

Default Copy Constructor Depicted

StringBad code StringBad::StringBad(const char *s) { len = std::strlen(s); str = new char[len + 1]; std::strcpy(str,s); num_strings++; cout << num_strings << “: \”” << str << “\” object created\n”; } StringBad::StringBad() { len = 4; str = new char[4]; std::strcpy(str, “C++”); num_strings++; cout << num_strings << “: \”” << str << “\” object created\n”; } StringBad::~StringBad() { cout << “\”” << str << “\” object deleted, “; --num_strings; cout << num_strings << “ left\n”; delete [] str; }

More code Int main() { StringBad headline1(“Celery stalks at midnight”); StringBad headline2(“Lettuce Prey”); StringBad sports(“Spinach leaves bowl for dollars”); callme1(headline1); callme2(headline2); StringBad sailor = sports; StringBad know; knot = headline } void callme1(StringBad &rsb) { cout << “String passed by reference:” << endl; cout << “ \”” << rsb << “\”\n”; } void callme1(StringBad sb) { cout << “String passed by value:” << endl; cout << “ \”” << sb << “\”\n”; }

Problem with copy constructor From previous example, –Two more objects are destroyed than constructed Program does create two more objects using default copy constructor. –Used to initialize the formal parameter of callme2() –Also used to initialize the object sailor to sports »Default copy constructor does not increment num_strings »The destructor does decrement num_strings »Destructors are called regardless of how objects are constructed. –Solution, provide an explicit copy constructor that does the update

Problem 2 copy constructor Implicit copy constructor copies by value –sailor.str = sports.str –Strings are not copied, the pointers are! It is a problem when the destructor is called –Deleting one object essentially deletes the string the other object points to This is because of the shallow copy.

Fixing the Problems Create your own explicit copy constructor –Make a deep copy! Make sure that the data and not the address is copied StringBad::StringBad(const StringBad &st) { num_strings++; len = st.len; str = new char [len + 1]; std::strcpy(str, st.str); cout << num_strings << “: \”” << str << “\” object created\n”; }

Depicted