Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

1 CSIS 123A Lecture 10 Inheritance

2 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

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

4 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?

5 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

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

7 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

8 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.

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

10 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

11 Base class and derived class II

12 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"

13 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); } };

14 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; }

15 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.

16 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

17 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

18 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”; }

19 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

20 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);

21 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.

22 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); };

23 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

24 Default Copy Constructor Depicted

25 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; }

26 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”; }

27 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

28 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.

29 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”; }

30 Depicted

31


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

Similar presentations


Ads by Google