SlideShare a Scribd company logo
1 of 8
Download to read offline
6.096 
Introduction to C++ January 19, 2011 Massachusetts Institute of Technology 
Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance 
We’ve already seen how to define composite datatypes using classes. Now we’ll take a step back and considertheprogrammingphilosophy underlying classes,known as object-oriented programming (OOP). 
1 The Basic Ideas of OOP 
Classic “procedural” programminglanguagesbeforeC++(such asC) oftenfocused onthe question “What should the program do next?” The way you structure a program in these languagesis: 
1. 
Split it up into a set of tasks and subtasks 
2. 
Make functions for the tasks 
3. 
Instruct the computer to perform them in sequence 
With large amounts of data and/or large numbers of tasks, this makes for complex and unmaintainableprograms. 
Consider the task of modeling the operation of a car. Such a program would have lots of separate variables storing information on various car parts, and there’d be no way to group together all the code that relates to, say, the wheels. It’s hard to keep all these variables and the connections between all the functions in mind. 
To manage this complexity, it’s nicer to package up self-sufficient, modular pieces of code. Peoplethinkoftheworldintermsofinteracting objects: we’dtalk aboutinteractionsbetween thesteering wheel,thepedals,thewheels,etc. OOPallowsprogrammerstopack awaydetails intoneat,self-containedboxes(objects)sothatthey canthink of theobjectsmoreabstractly and focus on the interactions between them. 
There are lots of definitions for OOP, but 3 primary features of it are: 
• 
Encapsulation: grouping relateddataandfunctionstogetherasobjectsanddefining an interface to those objects 
• 
Inheritance: allowing code to be reused between related types 
• 
Polymorphism: allowing a value to be one of several types, and determining at runtime which functions to call on it based on its type
Let’s see how each of these plays out in C++. 
2 Encapsulation 
Encapsulation just refers to packaging related stuff together. We’ve already seen how to package up data and the operations it supports in C++: with classes. 
If someone hands us a class, we do not need to know how it actually works to use it; all we need to know about is its public methods/data – its interface. This is often compared to operating a car: when you drive, you don’t care how the steering wheel makes the wheels turn; you just care that the interface the car presents (the steering wheel) allows you to accomplish your goal. If you remember the analogy from Lecture 6 about objects being boxes with buttons you can push, you can also think of the interface of a class as the set of buttons each instance of that class makes available. Interfaces abstract away the details of how all the operations are actually performed, allowing the programmer to focus on how objects will use each other’s interfaces – how they interact. 
This is why C++ makes you specify public and private access specifiers: by default, it assumes that the things you define in a class are internal details which someone using your code should not have to worry about. The practice of hiding away these details from client code is called “data hiding,” or making your class a “black box.” 
One way tothink about whathappensinan object-orientedprogramisthat wedefine what objects exist and what each one knows, and then the objects send messages to each other (bycalling each other’s methods) to exchange information and tell each other what to do. 
3 Inheritance 
Inheritance allows us to define hierarchies of related classes. 
Imaginewe’rewritinganinventoryprogramforvehicles,including carsand trucks. Wecould write one class for representing cars and an unrelated one for representing trucks, but we’d have to duplicate the functionality that all vehicles have in common. Instead, C++ allows us to specify the common code in a Vehicle class, and then specify that the Car and Truck classes share this code. 
The Vehicle class will be much the same as what we’ve seen before: 
1 2 3 4 
class Vehicle { protected : string license ; int year ; 
2
5 
6 public : 
7 Vehicle( const string &myLicense, const int myYear) 
8 : license(myLicense), year(myYear) {} 
9 const string getDesc() const 10 {return license + " from " + stringify(year);} 11 const string &getLicense() const {return license;} 12 const int getYear() const {return year;} 13 }; 
A few notes on this code, by line: 
2. 
The standard string classisdescribedinSection1 ofPS3; seetherefordetails. Recall that strings can be appended to each other with the + operator. 
3. 
protected is largely equivalent to private. We’ll discuss the differences shortly. 
8. This line demonstrates member initializer syntax. When defining a constructor, you sometimeswanttoinitializecertainmembers,particularly const members,evenbefore the constructor body. You simply put a colon before the function body, followed by a comma-separated list of items of the form dataMember(initialValue). 
10. This line assumes the existence of some function stringify forconverting numbersto strings. 
Now we want to specify that Car will inherit the Vehicle code, but with some additions. This is accomplished in line 1 below: 
1 class Car : public Vehicle { // Makes Car inherit from Vehicle 2 string style; 3 4 public : 5 Car( const string &myLicense, const int myYear, const string 
&myStyle) 
6 : Vehicle(myLicense, myYear), style(myStyle) {} 
7 const string &getStyle() {return style;} 
8 }; 
Now class Car has all the data members and methods of Vehicle, as well as a style data member and a getStyle method. 
Class Car inherits from class Vehicle. This is equivalent to saying that Car is a derived class, while Vehicle isits base class. You may also hear the terms subclass and superclass instead. 
Notes on the code: 
3
1. Don’t worry for now about why we stuck the public keywordinthere. 
6. Note how we use member initializer syntax to call the base-class constructor. We need to have a complete Vehicle object constructed before we construct the components addedinthe Car.Ifyoudonotexplicitly call abase-classconstructorusingthissyntax, the default base-class constructor will be called. 
Similarly, we could make a Truck classthatinheritsfrom Vehicle and sharesitscode. This would give a classhierarchy likethefollowing: 
Vehicle 
Truck 
Car 
Class hierarchies are generally drawn with arrows pointing from derived classes to base classes. 
3.1 Is-a vs. Has-a 
There are two ways we could describe some class A as depending on some other class B: 
1. 
Every A object has a B object. Forinstance,every Vehicle has a string object(called license). 
2. 
Every instance of A is a B instance. For instance, every Car is a Vehicle, as well. 
Inheritance allows us to define “is-a” relationships, but it should not be used to implement “has-a” relationships. It would be a design error to make Vehicle inherit from string because every Vehicle has a license; a Vehicle is not a string. “Has-a” relationships should be implemented by declaring data members, not by inheritance. 
3.2 Overriding Methods 
Wemight wanttogeneratethedescriptionfor Carsinadifferent wayfromgeneric Vehicles. To accomplish this, we can simply redefine the getDesc methodin Car, as below. Then, when we call getDesc on a Car object, it will use the redefined function. Redefining in this manner is called overriding thefunction. 
1 2 3 
class Car : public string style ; 
Vehicle 
{ 
// 
Makes 
Car 
inherit 
from 
Vehicle 
4
4 public : 
5 Car( const string &myLicense, const int myYear, const string &myStyle) 
6 : Vehicle(myLicense, myYear), style(myStyle) {} 7 const string getDesc() // Overriding this member function 8 {return stringify(year) + ’ ’ + style + ": " + license 
;} 9 const string &getStyle() {return style;} 10 }; 
3.2.1 Programming by Difference 
In defining derived classes, we only need to specify what’s different about them from their base classes. This powerful technique is called programmingbydifference. 
Inheritance allows only overriding methods and adding new members and methods. We cannot remove functionality that was present in the base class. 
3.3 Access Modifiers and Inheritance 
If we’d declared year and license as private in Vehicle, we wouldn’t be able to access them even from a derived class like Car. To allow derived classes but not outside code to access data members and member functions, we must declare them as protected. 
The public keyword usedin specifying abase class(e.g., class Car : public Vehicle {...})givesalimitforthevisibilityof theinherited methodsinthederived class. Normally you shouldjust use public here, which means that inherited methods declared as public are still public in the derived class. Specifying protected would make inherited methods, eventhosedeclared public,haveat most protected visibility. Forafull tableof theeffects of different inheritance access specifiers, see http://en.wikibooks.org/wiki/C++ Programming/Classes/Inheritance. 
4 Polymorphism 
Polymorphism means “many shapes.” It refers to the ability of one object to have many types. If we have a function that expects a Vehicle object, we can safely pass it a Car object, because every Car is also a Vehicle.Likewiseforreferencesandpointers: anywhere you can use a Vehicle *, you can use a Car *. 
5
4.1 virtual Functions 
There is still a problem. Take the following example: 
1 
Car 
c(" VANITY ", 
2003) ; 
2 
Vehicle 
* vPtr 
= 
&c; 
3 
cout 
<< 
vPtr -> getDesc (); 
(The-> notation online3justdereferences andgets a member. ptr->member is equivalent to (*ptr).member.) 
Because vPtr isdeclared asa Vehicle *,thiswill call the Vehicle versionof getDesc,even though the objectpointed tois actually a Car. Usually we’d wanttheprogramtoselectthe correct function at runtime based on which kind of object is pointed to. We can get this behavior by adding the keyword virtual before the method definition: 
1 class Vehicle { 
2 ... 
3 virtual const string getDesc() {...} 
4 }; 
With this definition, the code above would correctly select the Car version of getDesc. 
Selecting thecorrectfunctionat runtimeiscalled dynamicdispatch.Thismatchesthewhole OOP idea – we’re sending a message to the object and letting it figure out for itself what actions that message actually means it should take. 
Because references are implicitly using pointers, the same issues apply to references: 
1 
Car 
c(" VANITY ", 
2003) ; 
2 
Vehicle 
&v 
= 
c; 
3 
cout 
<< 
v. getDesc (); 
This will only call the Car version of getDesc if getDesc is declared as virtual. 
Once a method is declared virtual in some class C, it is virtual in every derived class of C, even if not explicitly declared as such. However, it is a good idea to declare it as virtual in the derived classes anyway for clarity. 
4.2 Pure virtual Functions 
Arguably,thereisnoreasonableway todefine getDesc forageneric Vehicle –onlyderived classes really need a definition of it, since there is no such thing as a generic vehicle that isn’t alsoacar,truck,orthelike. Still, wedowanttorequireeveryderived classof Vehicle tohavethisfunction. 
6
We can omit the definition of getDesc from Vehicle by making the function pure virtual via the following odd syntax: 
1 class Vehicle { 
2 ... 
3 virtual const string getDesc() = 0; // Pure virtual 
4 }; 
The =0 indicatesthat nodefinitionwillbegiven. Thisimpliesthat onecannolongercreate an instance of Vehicle; one can only create instances of Cars, Trucks, and other derived classes which do implement the getDesc method. Vehicle is then an abstract class – one which defines only an interface, but doesn’t actually implement it, and therefore cannot be instantiated. 
5 Multiple Inheritance 
Unlike many object-oriented languages, C++ allows a class to have multiple base classes: 
1 class Car : public Vehicle , public InsuredItem { 
2 ... 
3 }; 
ThisspecifiesthatCar shouldhaveallthemembersofboththe Vehicle andthe InsuredItem classes. 
Multiple inheritance is tricky and potentially dangerous: 
• 
Ifboth Vehicle and InsuredItem define a member x, you must remember to disambiguate which one you’re referring to by saying Vehicle::x or InsuredItem::x. 
• 
Ifboth Vehicle and InsuredItem inherited from the same base class, you’d end up with two instances of the base class within each Car (a “dreaded diamond”class hierarchy). There are ways to solve this problem, but it can get messy. 
In general, avoid multiple inheritance unless you know exactly what you’re doing. 
7
MIT OpenCourseWare 
http://ocw.mit.edu 
6.096 Introduction to C++ January (IAP) 2011 
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More Related Content

What's hot

What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 InterfaceOUM SAOKOSAL
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces Tuan Ngo
 
Classes And Methods
Classes And MethodsClasses And Methods
Classes And Methodsadil raja
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented ProgrammingGamindu Udayanga
 
IRJET- Inheritance in Java
IRJET- Inheritance in JavaIRJET- Inheritance in Java
IRJET- Inheritance in JavaIRJET Journal
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerVineet Kumar Saini
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with JavaJakir Hossain
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceOum Saokosal
 
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIObject Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIAjit Nayak
 

What's hot (19)

What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Chapter 9 Interface
Chapter 9 InterfaceChapter 9 Interface
Chapter 9 Interface
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
8815346
88153468815346
8815346
 
Interface
InterfaceInterface
Interface
 
Java interface
Java interfaceJava interface
Java interface
 
8 abstract classes and interfaces
8   abstract classes and interfaces 8   abstract classes and interfaces
8 abstract classes and interfaces
 
Classes And Methods
Classes And MethodsClasses And Methods
Classes And Methods
 
C++ Object Oriented Programming
C++  Object Oriented ProgrammingC++  Object Oriented Programming
C++ Object Oriented Programming
 
IRJET- Inheritance in Java
IRJET- Inheritance in JavaIRJET- Inheritance in Java
IRJET- Inheritance in Java
 
Top C Language Interview Questions and Answer
Top C Language Interview Questions and AnswerTop C Language Interview Questions and Answer
Top C Language Interview Questions and Answer
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Object Oriended Programming with Java
Object Oriended Programming with JavaObject Oriended Programming with Java
Object Oriended Programming with Java
 
C++ interview question
C++ interview questionC++ interview question
C++ interview question
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
C# concepts
C# conceptsC# concepts
C# concepts
 
Object Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part IIObject Oriented Programming using C++ Part II
Object Oriented Programming using C++ Part II
 
Abstract class
Abstract classAbstract class
Abstract class
 

Viewers also liked

Nicole concept map SPED 2200-04
Nicole concept map SPED 2200-04Nicole concept map SPED 2200-04
Nicole concept map SPED 2200-04caratozn
 
Val Josil Digital Photography
Val Josil Digital PhotographyVal Josil Digital Photography
Val Josil Digital PhotographyValery Josil
 
Axiologisi i
Axiologisi iAxiologisi i
Axiologisi iiodinou
 

Viewers also liked (6)

Nicole concept map SPED 2200-04
Nicole concept map SPED 2200-04Nicole concept map SPED 2200-04
Nicole concept map SPED 2200-04
 
Val Josil Digital Photography
Val Josil Digital PhotographyVal Josil Digital Photography
Val Josil Digital Photography
 
Integration cutural i
Integration cutural iIntegration cutural i
Integration cutural i
 
Axiologisi i
Axiologisi iAxiologisi i
Axiologisi i
 
E9
E9E9
E9
 
Lolaso
LolasoLolaso
Lolaso
 

Similar to C++ OOP Inheritance

Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1LK394
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Manykenatmxm
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionJI Ruan
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPTAjay Chimmani
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...NicheTech Com. Solutions Pvt. Ltd.
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]Rome468
 
Intro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesIntro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesBlue Elephant Consulting
 
Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Blue Elephant Consulting
 
CSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionCSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionJI Ruan
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010Rich Helton
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 

Similar to C++ OOP Inheritance (20)

Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1Cble assignment powerpoint activity for moodle 1
Cble assignment powerpoint activity for moodle 1
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08
 
Java oop concepts
Java oop conceptsJava oop concepts
Java oop concepts
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
CSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: AbstractionCSCI 383 Lecture 3 and 4: Abstraction
CSCI 383 Lecture 3 and 4: Abstraction
 
java tr.docx
java tr.docxjava tr.docx
java tr.docx
 
Java getstarted
Java getstartedJava getstarted
Java getstarted
 
Oopp Lab Work
Oopp Lab WorkOopp Lab Work
Oopp Lab Work
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
Objective of c in IOS , iOS Live Project Training Ahmedabad, MCA Live Project...
 
C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]C++ [ principles of object oriented programming ]
C++ [ principles of object oriented programming ]
 
Intro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm ReviewIntro To C++ - Class 14 - Midterm Review
Intro To C++ - Class 14 - Midterm Review
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
Intro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & ClassesIntro to C++ - Class 2 - Objects & Classes
Intro to C++ - Class 2 - Objects & Classes
 
Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++Intro To C++ - Class 2 - An Introduction To C++
Intro To C++ - Class 2 - An Introduction To C++
 
2 oop
2 oop2 oop
2 oop
 
CSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: AbstractionCSCI-383 Lecture 3-4: Abstraction
CSCI-383 Lecture 3-4: Abstraction
 
Intro Java Rev010
Intro Java Rev010Intro Java Rev010
Intro Java Rev010
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 

More from lksoo

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L8
L8L8
L8
 
L7
L7L7
L7
 
L6
L6L6
L6
 

Recently uploaded

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 

Recently uploaded (20)

CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 

C++ OOP Inheritance

  • 1. 6.096 Introduction to C++ January 19, 2011 Massachusetts Institute of Technology Lecture 7 Notes: Object-Oriented Programming (OOP) and Inheritance We’ve already seen how to define composite datatypes using classes. Now we’ll take a step back and considertheprogrammingphilosophy underlying classes,known as object-oriented programming (OOP). 1 The Basic Ideas of OOP Classic “procedural” programminglanguagesbeforeC++(such asC) oftenfocused onthe question “What should the program do next?” The way you structure a program in these languagesis: 1. Split it up into a set of tasks and subtasks 2. Make functions for the tasks 3. Instruct the computer to perform them in sequence With large amounts of data and/or large numbers of tasks, this makes for complex and unmaintainableprograms. Consider the task of modeling the operation of a car. Such a program would have lots of separate variables storing information on various car parts, and there’d be no way to group together all the code that relates to, say, the wheels. It’s hard to keep all these variables and the connections between all the functions in mind. To manage this complexity, it’s nicer to package up self-sufficient, modular pieces of code. Peoplethinkoftheworldintermsofinteracting objects: we’dtalk aboutinteractionsbetween thesteering wheel,thepedals,thewheels,etc. OOPallowsprogrammerstopack awaydetails intoneat,self-containedboxes(objects)sothatthey canthink of theobjectsmoreabstractly and focus on the interactions between them. There are lots of definitions for OOP, but 3 primary features of it are: • Encapsulation: grouping relateddataandfunctionstogetherasobjectsanddefining an interface to those objects • Inheritance: allowing code to be reused between related types • Polymorphism: allowing a value to be one of several types, and determining at runtime which functions to call on it based on its type
  • 2. Let’s see how each of these plays out in C++. 2 Encapsulation Encapsulation just refers to packaging related stuff together. We’ve already seen how to package up data and the operations it supports in C++: with classes. If someone hands us a class, we do not need to know how it actually works to use it; all we need to know about is its public methods/data – its interface. This is often compared to operating a car: when you drive, you don’t care how the steering wheel makes the wheels turn; you just care that the interface the car presents (the steering wheel) allows you to accomplish your goal. If you remember the analogy from Lecture 6 about objects being boxes with buttons you can push, you can also think of the interface of a class as the set of buttons each instance of that class makes available. Interfaces abstract away the details of how all the operations are actually performed, allowing the programmer to focus on how objects will use each other’s interfaces – how they interact. This is why C++ makes you specify public and private access specifiers: by default, it assumes that the things you define in a class are internal details which someone using your code should not have to worry about. The practice of hiding away these details from client code is called “data hiding,” or making your class a “black box.” One way tothink about whathappensinan object-orientedprogramisthat wedefine what objects exist and what each one knows, and then the objects send messages to each other (bycalling each other’s methods) to exchange information and tell each other what to do. 3 Inheritance Inheritance allows us to define hierarchies of related classes. Imaginewe’rewritinganinventoryprogramforvehicles,including carsand trucks. Wecould write one class for representing cars and an unrelated one for representing trucks, but we’d have to duplicate the functionality that all vehicles have in common. Instead, C++ allows us to specify the common code in a Vehicle class, and then specify that the Car and Truck classes share this code. The Vehicle class will be much the same as what we’ve seen before: 1 2 3 4 class Vehicle { protected : string license ; int year ; 2
  • 3. 5 6 public : 7 Vehicle( const string &myLicense, const int myYear) 8 : license(myLicense), year(myYear) {} 9 const string getDesc() const 10 {return license + " from " + stringify(year);} 11 const string &getLicense() const {return license;} 12 const int getYear() const {return year;} 13 }; A few notes on this code, by line: 2. The standard string classisdescribedinSection1 ofPS3; seetherefordetails. Recall that strings can be appended to each other with the + operator. 3. protected is largely equivalent to private. We’ll discuss the differences shortly. 8. This line demonstrates member initializer syntax. When defining a constructor, you sometimeswanttoinitializecertainmembers,particularly const members,evenbefore the constructor body. You simply put a colon before the function body, followed by a comma-separated list of items of the form dataMember(initialValue). 10. This line assumes the existence of some function stringify forconverting numbersto strings. Now we want to specify that Car will inherit the Vehicle code, but with some additions. This is accomplished in line 1 below: 1 class Car : public Vehicle { // Makes Car inherit from Vehicle 2 string style; 3 4 public : 5 Car( const string &myLicense, const int myYear, const string &myStyle) 6 : Vehicle(myLicense, myYear), style(myStyle) {} 7 const string &getStyle() {return style;} 8 }; Now class Car has all the data members and methods of Vehicle, as well as a style data member and a getStyle method. Class Car inherits from class Vehicle. This is equivalent to saying that Car is a derived class, while Vehicle isits base class. You may also hear the terms subclass and superclass instead. Notes on the code: 3
  • 4. 1. Don’t worry for now about why we stuck the public keywordinthere. 6. Note how we use member initializer syntax to call the base-class constructor. We need to have a complete Vehicle object constructed before we construct the components addedinthe Car.Ifyoudonotexplicitly call abase-classconstructorusingthissyntax, the default base-class constructor will be called. Similarly, we could make a Truck classthatinheritsfrom Vehicle and sharesitscode. This would give a classhierarchy likethefollowing: Vehicle Truck Car Class hierarchies are generally drawn with arrows pointing from derived classes to base classes. 3.1 Is-a vs. Has-a There are two ways we could describe some class A as depending on some other class B: 1. Every A object has a B object. Forinstance,every Vehicle has a string object(called license). 2. Every instance of A is a B instance. For instance, every Car is a Vehicle, as well. Inheritance allows us to define “is-a” relationships, but it should not be used to implement “has-a” relationships. It would be a design error to make Vehicle inherit from string because every Vehicle has a license; a Vehicle is not a string. “Has-a” relationships should be implemented by declaring data members, not by inheritance. 3.2 Overriding Methods Wemight wanttogeneratethedescriptionfor Carsinadifferent wayfromgeneric Vehicles. To accomplish this, we can simply redefine the getDesc methodin Car, as below. Then, when we call getDesc on a Car object, it will use the redefined function. Redefining in this manner is called overriding thefunction. 1 2 3 class Car : public string style ; Vehicle { // Makes Car inherit from Vehicle 4
  • 5. 4 public : 5 Car( const string &myLicense, const int myYear, const string &myStyle) 6 : Vehicle(myLicense, myYear), style(myStyle) {} 7 const string getDesc() // Overriding this member function 8 {return stringify(year) + ’ ’ + style + ": " + license ;} 9 const string &getStyle() {return style;} 10 }; 3.2.1 Programming by Difference In defining derived classes, we only need to specify what’s different about them from their base classes. This powerful technique is called programmingbydifference. Inheritance allows only overriding methods and adding new members and methods. We cannot remove functionality that was present in the base class. 3.3 Access Modifiers and Inheritance If we’d declared year and license as private in Vehicle, we wouldn’t be able to access them even from a derived class like Car. To allow derived classes but not outside code to access data members and member functions, we must declare them as protected. The public keyword usedin specifying abase class(e.g., class Car : public Vehicle {...})givesalimitforthevisibilityof theinherited methodsinthederived class. Normally you shouldjust use public here, which means that inherited methods declared as public are still public in the derived class. Specifying protected would make inherited methods, eventhosedeclared public,haveat most protected visibility. Forafull tableof theeffects of different inheritance access specifiers, see http://en.wikibooks.org/wiki/C++ Programming/Classes/Inheritance. 4 Polymorphism Polymorphism means “many shapes.” It refers to the ability of one object to have many types. If we have a function that expects a Vehicle object, we can safely pass it a Car object, because every Car is also a Vehicle.Likewiseforreferencesandpointers: anywhere you can use a Vehicle *, you can use a Car *. 5
  • 6. 4.1 virtual Functions There is still a problem. Take the following example: 1 Car c(" VANITY ", 2003) ; 2 Vehicle * vPtr = &c; 3 cout << vPtr -> getDesc (); (The-> notation online3justdereferences andgets a member. ptr->member is equivalent to (*ptr).member.) Because vPtr isdeclared asa Vehicle *,thiswill call the Vehicle versionof getDesc,even though the objectpointed tois actually a Car. Usually we’d wanttheprogramtoselectthe correct function at runtime based on which kind of object is pointed to. We can get this behavior by adding the keyword virtual before the method definition: 1 class Vehicle { 2 ... 3 virtual const string getDesc() {...} 4 }; With this definition, the code above would correctly select the Car version of getDesc. Selecting thecorrectfunctionat runtimeiscalled dynamicdispatch.Thismatchesthewhole OOP idea – we’re sending a message to the object and letting it figure out for itself what actions that message actually means it should take. Because references are implicitly using pointers, the same issues apply to references: 1 Car c(" VANITY ", 2003) ; 2 Vehicle &v = c; 3 cout << v. getDesc (); This will only call the Car version of getDesc if getDesc is declared as virtual. Once a method is declared virtual in some class C, it is virtual in every derived class of C, even if not explicitly declared as such. However, it is a good idea to declare it as virtual in the derived classes anyway for clarity. 4.2 Pure virtual Functions Arguably,thereisnoreasonableway todefine getDesc forageneric Vehicle –onlyderived classes really need a definition of it, since there is no such thing as a generic vehicle that isn’t alsoacar,truck,orthelike. Still, wedowanttorequireeveryderived classof Vehicle tohavethisfunction. 6
  • 7. We can omit the definition of getDesc from Vehicle by making the function pure virtual via the following odd syntax: 1 class Vehicle { 2 ... 3 virtual const string getDesc() = 0; // Pure virtual 4 }; The =0 indicatesthat nodefinitionwillbegiven. Thisimpliesthat onecannolongercreate an instance of Vehicle; one can only create instances of Cars, Trucks, and other derived classes which do implement the getDesc method. Vehicle is then an abstract class – one which defines only an interface, but doesn’t actually implement it, and therefore cannot be instantiated. 5 Multiple Inheritance Unlike many object-oriented languages, C++ allows a class to have multiple base classes: 1 class Car : public Vehicle , public InsuredItem { 2 ... 3 }; ThisspecifiesthatCar shouldhaveallthemembersofboththe Vehicle andthe InsuredItem classes. Multiple inheritance is tricky and potentially dangerous: • Ifboth Vehicle and InsuredItem define a member x, you must remember to disambiguate which one you’re referring to by saying Vehicle::x or InsuredItem::x. • Ifboth Vehicle and InsuredItem inherited from the same base class, you’d end up with two instances of the base class within each Car (a “dreaded diamond”class hierarchy). There are ways to solve this problem, but it can get messy. In general, avoid multiple inheritance unless you know exactly what you’re doing. 7
  • 8. MIT OpenCourseWare http://ocw.mit.edu 6.096 Introduction to C++ January (IAP) 2011 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.