Class Sale. Represents sales of single item with no added discounts or charges. Notice reserved word "virtual" in declaration of member function bill
|
|
- Stephany Robertson
- 5 years ago
- Views:
Transcription
1 Class Sale Represents sales of single item with no added discounts or charges. Notice reserved word "virtual" in declaration of member function bill Impact: Later, derived classes of Sale can define THEIR own versions of function bill Other member functions of Sale will use version based on the object instance of derived class! They won t automatically use Sale s version! ch 15-18
2 Derived Class DiscountSale Defined class DiscountSale : public Sale public: DiscountSale(); DiscountSale( double theprice, double the Discount); double getdiscount() const; void setdiscount(double newdiscount); virtual double bill() const; private: double discount; ; ch 15-19
3 DiscountSale s Implementation of bill() double DiscountSale::bill() const double fraction = discount/100; return (1 fraction)*getprice(); Qualifier "virtual" does not go in actual function definition "Automatically" virtual in derived class Declaration (in interface) not required to have "virtual" keyword either (but usually does) ch 15-20
4 DiscountSale s Implementation of bill() Virtual function in base class: "Automatically" virtual in derived class Derived class declaration (in interface) Not required to have "virtual" keyword But typically included anyway, for readability ch 15-21
5 Derived Class DiscountSale DiscountSale s member function bill() may be implemented differently than base class Sale s Particular to "discounts" Member functions savings() and "<" Will use this definition of bill() for all objects of DiscountSale class! Instead of "defaulting" to version defined in Sales class! ch 15-22
6 Virtual: Wow! Recall class Sale written long before derived class DiscountSale Members savings and "<" compiled before even had ideas of a DiscountSale class Yet in a call like: DiscountSale d1, d2; Sale *ps; ps = & d1; d1->savings(d2); Call in savings() to function bill() knows to use definition of bill() from DiscountSale class Powerful! ch 15-23
7 Late binding Virtual: How? Virtual functions implement late binding Tells compiler to "wait" until function is used in program Decide which definition to use based on calling object Very important OOP principle! ch 15-24
8 Overriding Virtual function definition changed in a derived class We say it has been "overidden" Similar to redefined Recall: for standard functions So: Virtual functions changed: overridden Non-virtual functions changed: redefined ch 15-25
9 Virtual Functions: Why Not All? Clear advantages to virtual functions as we ve seen Late binding easy to manage the derived classes from a (same) parent class One major disadvantage: overhead! Uses more storage Late binding is "on the fly", so programs run slower So if virtual functions not needed, should not be used ch 15-26
10 Pure Virtual Functions Base class might not have "meaningful" definition for some of its members! Its purpose is solely for others to derive from Recall class Figure All figures are objects of derived classes Rectangles, circles, triangles, etc. Class Figure has no idea how to draw! Make it a pure virtual function: virtual void draw() = 0; ch 15-27
11 Abstract Base Classes Pure virtual functions require no definition (implementation) Forces all derived classes to define "their own" version Class with one or more pure virtual functions is: abstract base class Can only be used as base class No objects can ever be created (instantiated) from it Since it doesn t have complete "definitions" of all its members! If derived class fails to define all pure s: It s an abstract base class too ch 15-28
12 Extended Type Compatibility Given: Derived is a derived class of Base Derived objects can be assigned to objects of type Base But NOT the other way! (Base class object is not a derived class object) (e.g., when animal is base class and dog and cat are derived classes, animal_object is not always a dog_object!) Consider previous example: A DiscountSale "is a" Sale, but reverse not true ( Sale is not always DiscountSale!) ch 15-29
13 Extended Type Compatibility Example class Pet public: string name; virtual void print() const; ; class Dog : public Pet public: string breed; virtual void print() const; ; Pet Dog ch 15-30
14 Class Pet and Class Dog Now given declarations: Dog vdog; Pet vpet; Notice member variables name and breed are public! For example purposes only! Not typical! ch 15-31
15 Using Classes Pet and Dog Anything that "is a" dog "is a" pet: vdog.name = "Tiny"; vdog.breed = "Great Dane"; vpet = vdog; These are allowable Can assign values to parent-types, but not reverse A pet "is not always a" dog (not necessarily) ch 15-32
16 Slicing Problem Notice value assigned to vpet "loses" its breed field! cout << vpet.breed; Produces ERROR msg! Called slicing problem Might seem appropriate Dog was moved to Pet variable, so it should be treated like a Pet And therefore pet does not have "dog" properties Makes for interesting philosphical debate ch 15-33
17 Slicing Problem Fix In C++, slicing problem is nuisance It still "is a" Great Dane named Tiny We d like to refer to its breed (GreatDane) even if it has been treated as a Pet Can do so with pointers to dynamic variables ch 15-34
18 Slicing Problem Example Pet *ppet; Dog *pdog; pdog = new Dog; pdog->name = "Tiny"; pdog->breed = "Great Dane"; ppet = pdog; Cannot access breed field of object pointed to by ppet: cout << ppet->breed; //ILLEGAL! ch 15-35
19 Slicing Problem Example Must use virtual member function: ppet->print(); Calls print() member function in Dog class! Because it s virtual C++ "waits" to see what object pointer ppet is actually pointing to before "binding" call ch 15-36
20 Virtual Destructors Recall: destructors needed to de-allocate dynamically allocated data Consider: Base *pbase = new Derived; delete pbase; Would call base class destructor even though pointing to Derived class object! Making destructor virtual fixes this! Good policy for all destructors to be virtual ch 15-37
21 Casting Consider: Pet vpet; Dog vdog; vdog = static_cast<dog>(vpet); //ILLEGAL! // Pet does not have all attributes defined in Dog! Can t cast a pet to be a dog, but: vpet = vdog; // Legal! vpet = static_cast<pet>(vdog); //Also legal! Upcasting is OK From descendant type to ancestor type ch 15-38
22 Downcasting Downcasting is dangerous! Casting from ancestor type to descended type Assumes information is "added" Can be done with dynamic_cast: Pet *ppet; ppet = new Dog; Dog *pdog = dynamic_cast<dog*>(ppet); Legal, but dangerous! Dog에는 Pet에정의되어있지않은정보도포함되어있으므로, down casting에서는일부정보가정의되지않은채로남아있게된다. ( 예 : Dog에는 breed 정보가정의되어있지만, Pet에는 breed 정보가없으므로, 위 assignment에서는 breed 정보가정의되어있지않은상태로남아있게된다.) Downcasting rarely done due to pitfalls Must track all information to be added All member functions must be virtual ch 15-39
23 Inner Workings of Virtual Functions Don t need to know how to use it! Principle of information hiding Virtual function table Compiler creates it Has pointers for each virtual member function Points to location of correct code for that function Objects of such classes also have pointer Points to virtual function table ch 15-40
24 Example of Inheritance with Virtual Function Inheritance Hierarchy Shape Circle Triangle Rectangle Sphere Prism Cube ch 15-41
25 /*** Shape.h */ #ifndef SHAPE_H #define SHAPE_H #include <string> using namespace std; class Shape friend ostream& operator<<(ostream &, Shape &); public: Shape(int pos_x, int pos_y, string cl); // constructor virtual ~Shape(); virtual double area() = 0; // pure virtual function (to be late bound) virtual double volume() = 0; // pure virtual function (to be late bound) virtual void print(ostream& fout) = 0; // pure virtual function (to be late bound) protected: int pos_x; // position x int pos_y; // position y string color; ; #endif ch 15-42
26 /** Shape.cpp */ #include <iostream> #include "Shape.h" using namespace std; Shape::Shape(int x, int y, string cl) :pos_x(x), pos_y(y), color(cl) cout << " Constructor (Shape). n"; Shape::~Shape() cout << " Destructor (Shape). n"; void Shape::print(ostream& fout) fout << "Shape: pos( << pos_x <<, << pos_y; fout << ), color ( << color << ")"; ostream& operator<<(ostream &ostr, Shape &shp) ostr << "Shape (" << shp.pos_x << ", ; ostr << shp.pos_y << ", << shp.color << ")"; return ostr; ch 15-43
27 /*** Circle.h */ #ifndef CIRCLE_H #define CIRCLE_H #include <string> #include "Shape.h" using namespace std; class Circle : public Shape friend ostream& operator<<(ostream &ostr, Circle &cir); public: Circle(int x, int y, int r, string clr); Circle(Circle &cir); // copy constructor virtual ~Circle(); double area(); double volume() return 0.0; void print(ostream& fout); int getradius(); void setradius(int r); Circle& operator++(); Circle& operator++(int dummy); protected: int radius; ; #endif ch 15-44
28 /** Circle.cpp (1) */ #include <iostream> #include "Circle.h" using namespace std; #define PI Circle::Circle(int x, int y, int r, string clr) :Shape(x, y, clr), radius(r) cout << " Constructor (Circle). n"; return; Circle::Circle(Circle & cir) :Shape(cir.pos_x, cir.pos_y, cir.color), radius (cir.radius) cout << " Copy constructor (Circle). n"; return; double Circle::area() double area; area = radius * radius * PI; return area; ch 15-45
29 /** Circle.cpp (2) */ void Circle::print(ostream& fout) fout << "Circle: pos(" << pos_x << ", " << pos_y << "), radius (" ; fout << radius << "), color(" << color << ), area(" << area() << ")"; int Circle::getRadius() return radius; void Circle::setRadius(int r) radius = r; Circle::~Circle() cout << " Destructor (Circle). n"; return; ostream& operator<<(ostream &ostr, Circle &cir) ostr << "Circle (radius:" << cir.getradius() << ", area:" << cir.area() << ")"; return ostr; ch 15-46
30 /** Circle.cpp (3) */ Circle& Circle::operator++() radius = radius + 1; return (*this); Circle& Circle::operator++(int dummy) Circle *pcir; pcir = new Circle(*this); radius = radius + 1; return *pcir; ch 15-47
31 /** Sphere.h */ #ifndef SPHERE_H #define SPHERE_H #include <string> #include "Circle.h" using namespace std; class Sphere : public Circle friend ostream& operator<<(ostream &ostr, Sphere &sph); public: Sphere(int x, int y, int r, string clr); Sphere(Sphere& sph); virtual ~Sphere(); double area(); double volume(); void print(ostream& fout); Sphere& operator++(); Sphere& operator++(int dummy); private: ; #endif ch 15-48
32 /** Sphere.cpp (1) */ #include <iostream> #include "Sphere.h" #include "Circle.h" using namespace std; #define PI Sphere::Sphere(int x, int y, int r, string clr) :Circle(x, y, r, clr) cout << " Constructor (Sphere). n"; Sphere::Sphere(Sphere& cyl) :Circle(cyl.pos_x, cyl.pos_y, cyl.radius, cyl.color) cout << " Copy constructor (Sphere). n"; Sphere::~Sphere() cout << " Destructor (Sphere). n"; double Sphere::area() double a = 0.0; a = 4.0*PI*radius*radius; return a; ch 15-49
33 /** Sphere.cpp (2) */ double Sphere::volume() double v = 0.0; v = (4.0*PI*radius*radius*radius)/3.0; return v; void Sphere::print(ostream& fout) fout << "Sphere: pos(" << pos_x << ", " << pos_y << "), radius (" << radius; fout << "), color(" << color << ), area(" << area() << "), volume << volume() << ) ; ostream& operator<<(ostream &ostr, Sphere &sph) ostr << "Sphere(radius:" << sph.getradius(); ostr << ", area:" << sph.area() << ", volume:" << sph.volume() << ")"; return ostr; ch 15-50
34 /** Sphere.cpp (3) */ Sphere& Sphere::operator++() // prefix increment radius++; return (*this); Sphere& Sphere::operator++(int dummy) // postfix increment Sphere *pcyl; pcyl = new Sphere(*this); radius++; return (*pcyl); ch 15-51
35 /** main.cpp (1) */ #include <iostream> #include <string> #include <fstream> #include "Shape.h" #include "Circle.h" #include "Square.h" #include "Sphere.h" #include "Cube.h" using namespace std; #define NUM_SHAPES 4 int main() ofstream fout; Shape *pshapes[num_shapes]; Circle *pcir; Sphere *psph; Square *psq; Cube *pcb; fout.open("output.txt"); if(fout.fail()) cout <<"Output.txt file opening failed n"; exit (1); ch 15-52
36 /** main.cpp (2) */ cout << "Creating Circle: n"; pcir = new Circle(1, 2, 3, "RED"); fout << *pcir << endl; cout << "Creating Square: n"; psq = new Square(1, 2, 3, "BLUE"); fout << *psq << endl; cout << "Creating Sphere: n"; psph = new Sphere(1, 2, 3, "YELLOW"); fout << *psph << endl; cout << "Creating Cube: n"; pcb = new Cube(1, 2, 3, "CYAN"); fout << *pcb << endl; pshapes[0] = pcir; pshapes[1] = psq; pshapes[2] = psph; pshapes[3] = pcb; for (int i=0; i<num_shapes; i++) fout << "pshapes[" << i <<"]->print(): "; pshapes[i]->print(fout); fout << endl; ch 15-53
37 /** main.cpp (3) */ fout << endl; fout << *psph << endl; fout << "prefix increment of Sphere: n"; cout << "prefix increment of Sphere: n"; fout << ++(*psph) << endl; fout << "postfix increment of Sphere: n"; cout << "postfix increment of Sphere: n"; (*psph)++; fout << *psph << endl; fout << endl; fout << *pcb << endl; fout << "prefix decrement of Cube: n"; cout << "prefix decrement of Cube: n"; fout << --(*pcb) << endl; fout << "postfix decrement of Cube: n"; cout << "postfix decrement of Cube: n"; (*pcb)--; fout << *pcb << endl ; cout << "Deleting Sphere: n" ; delete psph; cout << "Deleting Cube: n" ; delete pcb; // end of main() fout << endl << endl; fout.close(); ch 15-54
38 Execution Result (1) output.txt (2) Console output ch 15-55
39 Summary 15-1 Late binding delays decision of which member function is called until runtime In C++, virtual functions use late binding Pure virtual functions have no definition Classes with at least one are abstract No objects can be created from abstract class Used strictly as base for others to derive ch 15-56
40 Summary 15-2 Derived class objects can be assigned to base class objects Base class members are lost; slicing problem Pointer assignments and dynamic objects Allow "fix" to slicing problem Make all destructors virtual Good programming practice Ensures memory correctly de-allocated ch 15-57
41 Homework C++ programming with Inheritance, polymorphism and virtual function: shape, point, square, circle, and regular triangle Class Shape contains public member methods: virtual print(); virtual area(); By default, method area() returns 0.0 as result. Class Point inherits from class Shape, contains protected data members of double x; double y; and initializes x = 0.0 and y = 0.0 at default constructor. Class Rectangle inherits from class Point, contains protected data member double width, and initializes width = 0.0 at default constructor. Class Circle inherits from class Point, contains protected data member double radius, and initializes radius = 0.0 at default constructor. Class Triangle inherits from class Point, contains protected data members double side, double height, and initializes side = 0.0 and height = 0.0 at default constructor. Class Square, Circle and Triang have member method double area() const; to calculate the area of each shape, and print() to print ShapeName. Polymorphism should be provided using virtual function print() at Class Shape and Class Point that is dynamically binding into the print() method of Class Square, Circle and Triang. ch 15-58
42 main() Shape *shape[3]; Rectangle rec(1,2,3); Circle cl(4); Triangle tri(5,6) shape[0] = &rec; shape[1] = &cl; shape[2] = &tri; for (int i = 0; i< 3; i++) arr_shape[i] -> print(); cout << area is : << arr_shape[i] -> area() << endl; Programming Projects Programming Projects 15-2 ch 15-59
Chapter 15. Polymorphism and Virtual Functions. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 15 Polymorphism and Virtual Functions Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Virtual Function Basics Late binding Implementing virtual functions When to
More informationVirtual functions concepts
Virtual functions concepts l Virtual: exists in essence though not in fact l Idea is that a virtual function can be used before it is defined And it might be defined many, many ways! l Relates to OOP concept
More informationInheritance. Overview. Chapter 15 & additional topics. Inheritance Introduction. Three different kinds of inheritance
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Motivating
More informationInheritance. Chapter 15 & additional topics
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance
More informationInheritance. Chapter 15 & additional topics
Inheritance Chapter 15 & additional topics Overview Inheritance Introduction Three different kinds of inheritance Changing an inherited member function More Inheritance Details Polymorphism Inheritance
More information15: Polymorphism & Virtual Functions
15: Polymorphism & Virtual Functions 김동원 2003.02.19 Overview virtual function & constructors Destructors and virtual destructors Operator overloading Downcasting Thinking in C++ Page 1 virtual functions
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationQUIZ. Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed?
QUIZ Write the following for the class Bar: Default constructor Constructor Copy-constructor Overloaded assignment oper. Is a destructor needed? Or Foo(x), depending on how we want the initialization
More informationInheritance (with C++)
Inheritance (with C++) Starting to cover Savitch Chap. 15 More OS topics in later weeks (memory concepts, libraries) Inheritance Basics A new class is inherited from an existing class Existing class is
More informationInheritance Basics. Inheritance (with C++) Base class example: Employee. Inheritance begets hierarchies. Writing derived classes
Inheritance (with C++) Starting to cover Savitch Chap. 15 More OS topics in later weeks (memory concepts, libraries) Inheritance Basics A new class is inherited from an existing class Existing class is
More informationChapter 20 - C++ Virtual Functions and Polymorphism
Chapter 20 - C++ Virtual Functions and Polymorphism Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes 20.5 Polymorphism
More informationChapter 11. The first objective here is to make use of the list class definition from a previous lab. Recall the class definition for ShapeList.
Chapter 11 A portion of this lab is to be done during the scheduled lab time. The take-home programming assignment is to be turned in before the next lab; see the lab website. The in-lab portion is worth
More informationPolymorphism Part 1 1
Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationPolymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University
Polymorphism Miri Ben-Nissan (Kopel) 1 Shape Triangle Rectangle Circle int main( ) Shape* p = GetShape( ); p->draw( ); Shape* GetShape( ) choose randomly which shape to send back For example: Shape* p
More informationPOLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE
Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public
More informationPOLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors
POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual
More informationWhat is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1
Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult
More informationCS250 Intro to CS II. Spring CS250 - Intro to CS II 1
CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining
More informationObject Oriented Programming COP3330 / CGS5409
Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data
More informationIntroduction to C++: Part 4
Introduction to C++: Part 4 Tutorial Outline: Part 3 Virtual functions and inheritance Look at a real and useful C++ class Square Let s make a subclass of Rectangle called Square. Open the NetBeans project
More informationC++ Crash Kurs. Polymorphism. Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck
C++ Crash Kurs Polymorphism Dr. Dennis Pfisterer Institut für Telematik, Universität zu Lübeck http://www.itm.uni-luebeck.de/people/pfisterer C++ Polymorphism Major abstractions of C++ Data abstraction
More informationCS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4
CS32 - Week 4 Umut Oztok Jul 15, 2016 Inheritance Process of deriving a new class using another class as a base. Base/Parent/Super Class Derived/Child/Sub Class Inheritance class Animal{ Animal(); ~Animal();
More informationECE 3574: Dynamic Polymorphism using Inheritance
1 ECE 3574: Dynamic Polymorphism using Inheritance Changwoo Min 2 Administrivia Survey on class will be out tonight or tomorrow night Please, let me share your idea to improve the class! 3 Meeting 10:
More informationChapter 19 - C++ Inheritance
Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions
More informationModule 7 b. -Namespaces -Exceptions handling
Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides
More informationChapter 19 C++ Inheritance
Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes
More informationAbsolute C++ Walter Savitch
Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents
More informationTime(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }
Inheritance The following class implements time in hh:mm::ss format: class { public: () { = 0; = 0; = 0; (int h, int m, int s) { = h; = m; = s; void set(int h, int m, int s) { = h; = m; = s; void tick()
More informationDistributed Real-Time Control Systems. Chapter 13 C++ Class Hierarchies
Distributed Real-Time Control Systems Chapter 13 C++ Class Hierarchies 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according
More informationData Structures and Other Objects Using C++
Inheritance Chapter 14 discuss Derived classes, Inheritance, and Polymorphism Inheritance Basics Inheritance Details Data Structures and Other Objects Using C++ Polymorphism Virtual Functions Inheritance
More informationPolymorphism. Zimmer CSCI 330
Polymorphism Polymorphism - is the property of OOP that allows the run-time binding of a function's name to the code that implements the function. (Run-time binding to the starting address of the code.)
More informationVIRTUAL FUNCTIONS Chapter 10
1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions
More informationIntroduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1
Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1 Inheritance Consider a new type Square. Following how we declarations for the Rectangle and Circle classes we could declare it as follows:
More informationWhere do we stand on inheritance?
In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public
More informationObject Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:
Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name: Section 1 Multiple Choice Questions (40 pts total, 2 pts each): Q1: Employee is a base class and HourlyWorker is a derived class, with
More informationInheritance, Polymorphism, and Interfaces
Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 22 November 28, 2016 CPSC 427, Lecture 22 1/43 Exceptions (continued) Code Reuse Linear Containers Ordered Containers Multiple Inheritance
More informationNamespaces and Class Hierarchies
and 1 2 3 MCS 360 Lecture 9 Introduction to Data Structures Jan Verschelde, 13 September 2010 and 1 2 3 Suppose we need to store a point: 1 data: integer coordinates; 2 functions: get values for the coordinates
More informationUNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.
y UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I Lab Module 7 CLASSES, INHERITANCE AND POLYMORPHISM Department of Media Interactive
More informationClasses - 2. Data Processing Course, I. Hrivnacova, IPN Orsay
Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member
More informationVALLIAMMAI ENGINEERING COLLEGE
VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED
More informationInheritance and aggregation
Advanced Object Oriented Programming Inheritance and aggregation Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Inheritance? Extend a class to create a new class
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationUse the template below and fill in the areas in Red to complete it.
C++ with Inheritance Pproblem involving inheritance. You have to finish completing code that creates a class called shape, from which 3 classes are derived that are called square and triangle. I am giving
More informationCS105 C++ Lecture 7. More on Classes, Inheritance
CS105 C++ Lecture 7 More on Classes, Inheritance " Operator Overloading Global vs Member Functions Difference: member functions already have this as an argument implicitly, global has to take another parameter.
More informationCSS 343 Data Structures, Algorithms, and Discrete Math II. Polymorphism. Yusuf Pisan
CSS 343 Data Structures, Algorithms, and Discrete Math II Polymorphism Yusuf Pisan Polymorphism Hierarchy of classes that are related by inheritance static linkage / early binding Decide on function to
More informationJava Object Oriented Design. CSC207 Fall 2014
Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code
More informationCS 225. Data Structures
CS 5 Data Structures 1 2 3 4 5 6 7 8 9 10 11 #include using namespace std; int main() { int *x = new int; int &y = *x; y = 4; cout
More informationSRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR
SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name
More informationPolymorphism CSCI 201 Principles of Software Development
Polymorphism CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Program Outline USC CSCI 201L Polymorphism Based on the inheritance hierarchy, an object with a compile-time
More informationInheritance (Deitel chapter 9)
Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance
More informationHomework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine
Homework 6 Yuji Shimojo CMSC 330 Instructor: Prof. Reginald Y. Haseltine July 21, 2013 Question 1 What is the output of the following C++ program? #include #include using namespace
More informationObject-Oriented Concept
Object-Oriented Concept Encapsulation ADT, Object Inheritance Derived object Polymorphism Each object knows what it is Polymorphism noun, the quality or state of being able to assume different forms -
More informationCS 162, Lecture 25: Exam II Review. 30 May 2018
CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you
More informationMidterm Exam 5 April 20, 2015
Midterm Exam 5 April 20, 2015 Name: Section 1: Multiple Choice Questions (24 pts total, 3 pts each) Q1: Which of the following is not a kind of inheritance in C++? a. public. b. private. c. static. d.
More informationInheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017
OOP components For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Data Abstraction Information Hiding, ADTs Encapsulation Type Extensibility Operator Overloading
More informationChapter 8. Operator Overloading, Friends, and References. Copyright 2010 Pearson Addison-Wesley. All rights reserved
Chapter 8 Operator Overloading, Friends, and References Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives Basic Operator Overloading Unary operators As member functions Friends
More informationCSCI 104 Polymorphism. Mark Redekopp David Kempe
CSCI 104 Polymorphism Mark Redekopp David Kempe Virtual functions, Abstract classes, and Interfaces POLYMORPHISM 2 Assignment of Base/Declared Can we assign a derived object into a base object? Can we
More informationReview: C++ Basic Concepts. Dr. Yingwu Zhu
Review: C++ Basic Concepts Dr. Yingwu Zhu Outline C++ class declaration Constructor Overloading functions Overloading operators Destructor Redundant declaration A Real-World Example Question #1: How to
More informationCasting and polymorphism Enumeration
Casting and polymorphism Enumeration Shahram Rahatlou http://www.roma1.infn.it/people/rahatlou/programmazione++/ Corso di Programmazione++ Roma, 25 May 2009 1 Polymorphic vector of Person vector
More informationLaboratory 7. Programming Workshop 2 (CSCI 1061U) Faisal Qureshi.
Laboratory 7 Programming Workshop 2 (CSCI 1061U) Faisal Qureshi http://faculty.uoit.ca/qureshi C++ Inheritance Due back on Saturday, March 25 before 11:59 pm. Goal You are asked to create a commandline-based
More informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More informationInterview Questions of C++
Interview Questions of C++ Q-1 What is the full form of OOPS? Ans: Object Oriented Programming System. Q-2 What is a class? Ans: Class is a blue print which reflects the entities attributes and actions.
More information04-24/26 Discussion Notes
04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x
More informationIncreases Program Structure which results in greater reliability. Polymorphism
UNIT 4 C++ Inheritance What is Inheritance? Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the
More informationPOLYMORPHISM. Phone : (02668) , URL :
POLYMORPHISM POLYMORPHISM Polymorphism is the property of the same object to behave differently in different context given the same message Compile Time and Runtime Polymorphism Compile time - Function
More informationC++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.
Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack
More informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e 1992-2010 by Pearson Education, Inc. All Rights Reserved. 1 Standard Behavior: When the compiler is working out which member function to call, it selects according to the type of
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
More informationObject Oriented Programming: Inheritance Polymorphism
Object Oriented Programming: Inheritance Polymorphism Shahram Rahatlou Computing Methods in Physics http://www.roma1.infn.it/people/rahatlou/cmp/ Anno Accademico 2018/19 Today s Lecture Introduction to
More informationPOLYMORPHISM Polymorphism: the type Polymorphism taking many shapes type of object
1 License: http://creativecommons.org/licenses/by-nc-nd/3.0/ POLYMORPHISM There are three major concepts in object-oriented programming: 1. Encapsulation (Classes), Data abstraction, information hiding
More informationC++ Programming: Polymorphism
C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function
More informationProgramming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur
Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module
More informationSoftware Paradigms (Lesson 3) Object-Oriented Paradigm (2)
Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3
More informationC How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e 1992-2010 by Pearson Education, Inc. All Rights Reserved. 1 Inheritance is a form of software reuse in which you create a class that absorbs an existing class s data and behaviors
More informationInheritance, polymorphism, interfaces
Inheritance, polymorphism, interfaces "is-a" relationship Similar things (sharing same set of attributes / operations): a group / concept Similar groups (sharing a subset of attributes / operations): a
More information(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University
(12-1) OOP: Polymorphism in C++ D & D Chapter 12 Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University Key Concepts Polymorphism virtual functions Virtual function tables
More informationCh 14. Inheritance. September 10, Prof. Young-Tak Kim
2013-2 Ch 14. Inheritance September 10, 2013 Advanced Networking Technology Lab. (YU-ANTL) Dept. of Information & Comm. Eng, Graduate School, Yeungnam University, KOREA (Tel : +82-53-810-2497; Fax : +82-53-810-4742
More informationLesson Plan. Subject: OBJECT ORIENTED PROGRAMMING USING C++ :15 weeks (From January, 2018 to April,2018)
Lesson Plan Name of the Faculty Discipline Semester :Mrs. Reena Rani : Computer Engineering : IV Subject: OBJECT ORIENTED PROGRAMMING USING C++ Lesson Plan Duration :15 weeks (From January, 2018 to April,2018)
More informationMore C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com
More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes
More informationData type of a pointer must be same as the data type of the variable to which the pointer variable is pointing. Here are a few examples:
Unit IV Pointers and Polymorphism in C++ Concepts of Pointer: A pointer is a variable that holds a memory address of another variable where a value lives. A pointer is declared using the * operator before
More informationProgramming in C++: Assignment Week 6
Programming in C++: Assignment Week 6 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur 721302 partha.p.das@gmail.com April 6, 2017
More informationCS 225. Data Structures. Wade Fagen-Ulmschneider
CS 225 Data Structures Wade Fagen-Ulmschneider 11 15 16 17 18 19 20 21 22 23 24 /* * Creates a new sphere that contains the exact volume * of the volume of the two input spheres. */ Sphere joinspheres(const
More informationModern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi
Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance
More informationDistributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III
Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according
More informationCS OBJECT ORIENTED PROGRAMMING
UNIT-4 INHERITANCE AND RUN TIME POLYMORPHISM Inheritance public, private, and protected derivations multiple inheritance virtual base class abstract class composite objects Runtime polymorphism virtual
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic
More informationCS11 Introduction to C++ Fall Lecture 7
CS11 Introduction to C++ Fall 2012-2013 Lecture 7 Computer Strategy Game n Want to write a turn-based strategy game for the computer n Need different kinds of units for the game Different capabilities,
More informationLecture 14: more class, C++ streams
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:
More informationOOP Fundamental Concepts
Polymorphism Dr. Sanem Sarıel Talay 1 OOP Fundamental Concepts 1. Encapsulation (Classes) Data abstraction, information hiding 2. Inheritance Is a relation, reusability 3. Polymorphism Run time decision
More information1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks.
1.124 Quiz 1 Thursday October 8, 1998 Time: 1 hour 15 minutes Answer all questions. All questions carry equal marks. Question 1. The following code is to be built and run as follows: Compile as Link as
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428
More informationRAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING QUESTION BANK UNIT I 2 MARKS
RAJIV GANDHI COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF INFORMATION TECHNOLOGY OBJECT ORIENTED PROGRAMMING YEAR/SEM:II & III UNIT I 1) Give the evolution diagram of OOPS concept. 2) Give some
More informationObject Oriented Programming. Solved MCQs - Part 2
Object Oriented Programming Solved MCQs - Part 2 Object Oriented Programming Solved MCQs - Part 2 It is possible to declare as a friend A member function A global function A class All of the above What
More informationCSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism
CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism Review from Lecture 22 Added parent pointers to the TreeNode to implement increment and decrement operations on tree
More informationObject-Oriented Principles and Practice / C++
Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered
More informationCPSC 427: Object-Oriented Programming
CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 19 November 7, 2018 CPSC 427, Lecture 19, November 7, 2018 1/18 Exceptions Thowing an Exception Catching an Exception CPSC 427, Lecture
More informationPolymorphism. VII - Inheritance and Polymorphism
Polymorphism Polymorphism is implemented when you have (a) derived class(es) containing a member function with the same signature as a base class. A function invoked through a pointer or a reference to
More information