POLYMORPHISM. Phone : (02668) , URL :
|
|
- Lily Parsons
- 5 years ago
- Views:
Transcription
1 POLYMORPHISM
2 POLYMORPHISM Polymorphism is the property of the same object to behave differently in different context given the same message
3 Compile Time and Runtime Polymorphism Compile time - Function Overloading, Operator Overloading Run time - Virtual function with inheritance
4 Pointer to Object Normal objects cannot help in achieving runtime polymorphism It is possible to achieve it only by setting or defining pointer to objects
5 Pointer to Object Class demo.. demo DemoObj; demo *ptrdemoobj; ptrdemoobj = & DemoObj; Look at the code above. Pointer to object is similar to other pointers with no difference
6 this Pointer The this pointer is a pointer to an object invoked by the member function. Following code explains the usage of this pointer. #include<iostream.h> #include<string.h> using namespace std; class person string name; int age; person(string tempname, int tempage) name = tempname; age = tempage; person elder (person otherperson) if(age>otherperson.age) return *this; //returning the invoking object else return otherperson; friend ostream & operator << (ostream & tempout, person & tempperson); ; ostream & operator << (ostream & tempout, person & tempperson) tempout << "The person "<<tempperson.name<<" is " << tempperson.age << " years old\n"; return tempout; void main() person Steve( Steve Waugh", 35); person Mark( Mark Waugh", 20); person bigbrother = Steve.elder(B); cout<<bigbrother; Output of the Programme The person Steve Waugh is 35 years old This example shows how *this returns the elder brothers object. Steve is an elder brother. So when we call Steve.elder(Mark) the function elder is called where the age of invoking the object is compared with the age of Mark s object. Steve s age is more. So *this is returned from the function.
7 Compatibility of Derived and Base Class Pointers Base class pointers can point to a derived class object No casting is required Look at the following code BaseClass BC; DerivedClass DC : public BaseClass; BaseClass *ptrbc; DerivedClass ptrdc; ptrbc = &BC; ptrdc = &DC; ptrbc = &DC; ptrdc = &BC; //pointer and content are of similar types //pointer and content are of similar types // this is done without any casting // not allowed
8 Compatibility of Derived and Base Class Pointers Though the derived class and base class pointers seem compatible, there are some points to note. 1. Base class pointer can be made to point to a derived class object, but is cannot access the original members of the derived class. It can only access base class members of the derived class object. The base class pointer can see only base class subobject embedded in the derived class object, not the additional part of the derived class. However, if any of the functions defined in derived class is defined as virtual in base class, the case will be different. 2. In no case, derived class object pointer is made to point to the base class. It can only be done by casting. i.e. ptrdc = &BC will give error, but ptrdc = (DC *) &BC will work. 3. The increment and decrement operator with base pointer types do not behave as expected. A base class pointer is always incremented as per the base class size and a derived class pointer is always incremented as per the derived class size. Hence, if a base class pointer is pointing to a derived class object, after increment, it might not point to the next derived object.
9 Subobject Concept Whenever a base class is inherited, the derived class contains the base class subobject In case of multiple inheritance, the derived class contains multiple subobjects. In case of multilevel inheritance, we have n subobjects in the class derived at n+1 level Compiler automatically manages the pointer to point to the respective subobject of the derived class in case of multiple or multilevel inheritance e.g. BaseClass1 BC1; BaseClass2 BC2; DerivedClass dc : public BaseClass1, BaseClass2; BaseClass1 *ptrbc1; BaseClass2 *ptrbc2; DerivedClass ptrdc; ptrbc1 = &DC; ptrbc2 = &DC; // point to subobject of BaseClass1 // point to subobject of BaseClass2
10 Base Class and Derived Class Member Functions It is possible to have two different member functions with the same name, one in base class and other in derived class The function in the derived class is known as overloaded function in this case It is analogues to having a global and a local variable with the same name So, if we refer to a function in derived class, the derived class function is executed It is interesting to check the case where the pointer to the base class is made to point to derived class, and the overloaded function is called using that pointer.
11 Base Class and Derived Class Member Functions #include<iostream.h> #include<string.h> using namespace std; class shape int linestyle; int fillcoller; void draw() cout<<"shape is drawn \n"; ; class circle:public shape int radius; int centerpointx,centerpointy; void draw() cout<<"circle is drawn \n"; ; void main() Output of program Shape is drawn Circle is drawn Shape is drawn shape someshape, *ptrshape; circle ring; someshape.draw(); ring.draw(); ptrshape = ˚ ptrshape->draw(); // When we use a base class pointer pointing to the derived class, the function called is from the base class, not from the derived class
12 Base Class and Derived Class Member Functions #include<iostream.h> #include<string.h> using namespace std; class shape int linestyle; int fillcoller; virtual void draw() cout<<"shape is drawn \n"; ; class circle:public shape int radius; int centerpointx; int centerpointy; void draw() cout<<"circle is drawn \n"; ; class rectangle:public shape int lefttopx; int lefttopy; int rightbottomx; int rightbottomy; someotherfunctin() //no draw defined here // nothing ; void main() shape someshape, *ptrshape; circle ring; someshape.draw(); ring.draw(); ptrshape = ˚ ptrshape->draw(); rectangle square; ptrshape = □ ptrshape->draw(); // this would still call draw() of shape chass Output of the Program Shape is drawn Circle is drawn Circle is drawn Shape is drawn Notice the Change. Now ptrshape->draw() calls draw() of circle, not shape. In base class the function is defined as virtual. The addition of word virtual makes the whole difference. When the statement ptrshape->draw() is exucuted, it looks at the content of the ptrshape at runtime, and then executes the draw() function which is appropriate. This is the difference when we use virtual function instead of normal function
13 Virtual Functions Virtual functions are special They are treated differently by the compiler The class has an additional storage requirement when at least one virtual function is defined inside it A table is created additionally to store pointers to all virtual functions available to all the objects of the class. The table is called virtual table A single pointer to the virtual table is inserted in all class objects when the class contains at least one virtual function This pointer is known as vptr Whenever an object of such class wants to execute a virtual function, the table is referred to and the appropriate function is called
14 Virtual Functions Few syntactical constraints on use of virtual functions: 1. The function name must be preceded by virtual keyword in the base class 2. The function in the derived class must have the same name as of the virtual function defined in the base class and the same prototype. If the prototype is different, the function is as good as overloaded function and not treated as virtual function 3. The function in the derived class need not be preceded by the virtual keyword. If it is preceded by virtual keyword, it makes no difference 4. If a function with the same name is not defined in the derived class, the original base class function is invoked. 5. The virtual function must be defined in the base class; it may have an empty body though
15 Virtual Functions 6. For any real problem solving case using virtual function, the class hierarchy should be present. The virtual functions are the members of the classes of the hierarchy. They are called using either pointer to the base class or a reference to base class. This implies that the functions must be members of base as well as derived class, respectively 7. Polymorphism is achieved only using pointers to the base class. It is not possible using objects. This known as static invocation of virtual function 8. Virtual constructors are not possible. Constructing a derived class object needs specific construction of the base class subobject within. Obviously, their constructors cannot be virtual. When an object is deleted, we may have virtual destructor for destroying them, so the delete <pointer> operation works for the object pointed to, irrespective of the pointer type. Here, it is allowed to provide deletion of the entire derived class object while pointed to by a base class pointer. (otherwise it would only delete base class subobject of the derived class). Anyway, it is a good idea to have virtual destructors to avoid memory leaks
16 Default Arguments to Virtual Functions #include<iostream.h> #include<string.h> using namespace std; class shape int linestyle; int fillcoller; virtual int draw(int size=100) cout<<"shape is drawn \n"; return size; ; class circle:public shape int radius; int centerpointx; int centerpointy; int draw(int size=200) cout<<"circle is drawn \n"; return size; ; void main() shape someshape, *ptrshape; circle ring; someshape.draw(); ring.draw(); ptrshape = ˚ // base class pointer pointing to derived class // object int drawsize = ptrshape->draw(); // now this draws a circle cout<<"draw size for circle using a base class pointer is : "<<drawsize<<endl; // displays 100 instead of 200 circle *ptrcircle = ˚ //now we are using a derived class //pointer to point to a derived class // object drawsize=ptrcircle->draw(); cout<<"draw size for circle using a base class pointer is : "<<drawsize<<endl; // display 200 correctly Output of the program Shape is drawn Circle is drawn Draw size for circle using a base class pointer is 100 Circle is drawn Draw size for circle using a derived class pointer is 200
17 Default Arguments to Virtual Functions When we use a base class pointer to point to a derived class object, the default value of the base class function will be taken. Here the function which is executed is correct, but with the default value of the base class. On the other hand when we use a derived class pointer, the default value of derived class function is taken. Therefore, we cannot use default parameters like a normal function here. The solution here is to provide a local variable initialized in both such classes and then to use default argument. If we need default arguments, they can be assigned values of such local variables as in the next example. We only need to see if the user has supplied a value, if not, the user has supplied a value by keeping a dummy default argument. If the argument equals to the dummy argument, the use has not supplied a value and we can take the value from the local variable.
18 Default Arguments to Virtual Functions #include<iostream.h> #include<string.h> class shape int linestyle; int fillcoller; virtual int draw(int size=1) cout<<"shape is drawn \n"; int shapesize = 100; if(size==1) // default case size = shapesize; return size; ; class circle:public shape int radius; int centerpointx; int centerpointy; int draw(int size=1) cout<<"circle is drawn \n"; int circlesize = 200; if(size==1) // default case size = circlesize; return size; ; void main() shape someshape, *ptrshape; circle ring; someshape.draw(); ring.draw(); ptrshape = ˚ // base class pointer pointing to derived class //object int drawsize = ptrshape->draw(); // now this drows a circle cout<<"draw size for circle using a base class pointer is : <<drawsize<<endl; circle *ptrcircle = ˚ // now we are using a derived class //pointer to point to a derived class object drawsize=ptrcircle->draw(); cout<<"draw size for circle using a derived class pointer is : <<drawsize<<endl; Output of the Program Shape is drawn Circle is drawn Circle is drawn Draw size for circle using a base class pointer is : 200 Circle is drawn Draw size for circle using a derived class pointer is : 200
19 Using Virtual Functions #include<iostream.h> #include<ctime.h> class figure; // forward declaration class point int x,y; point(int tempx=0, int tempy=0) x = tempx; y = tempy; int getx() const return x; int gety() const return y; friend ostream & operator << (ostream & tempout, point & temppoint); ; ostream & operator << (ostream & tempout, point & temppoint) tempout<< "( "<<temppoint.getx() << ", "<< temppoint.gety() << " )"; return tempout; ; class shape point position; int color; virtual void draw() cout<<" Shape is drawn "; friend figure; // frgure is going to use parameters for drawing shapes ; class square:public shape point leftbottom; int length; square(point templeftbuttom, int templength) leftbottom = templeftbuttom; length = templength; void draw() cout<<"square is drawn at " << leftbottom << " and with length as " << length <<endl;
20 Using Virtual Functions class triangle:public shape point Avertex, Bvertex, Cvertex; triangle(point tempavertex, point tempbvertex, point tempcvertex) Avertex=tempavertex; Bvertex=tempbvertex; Cvertex=tempcvertex; void draw() cout<< "Triangle is drawn at " << Avertex <<" " <<Bvertex << " " << Cvertex << endl; ; class circle:public shape point center; int radius; circle(point tempcenter, int tempradius) center = tempcenter; radius = tempradius; void draw() cout<< "Circle is drawn at " << center <<" and the radius is " << radius << endl; ; class figure shape * images[25]; figure() srand( (unsigned)time( NULL ) ); for(int i=0; i<25; i++) int randomvalues[6]; for(int j=0; j<6; j++) randomvalues[i] = rand() % 50; point position1(randomvalues[0], randomvalues[1]); point position2(randomvalues[2], randomvalues[3]); point position3(randomvalues[4], randomvalues[5]); switch(int choice = rand() % 3) case 0: int length = rand() % 20; images[i] = new square(position1, length); break;
21 Using Virtual Functions ; case 1: images[i] = new triangle(position1, position2, position3); break; case 2: int radius = rand() % 10; images[i] = new circle(position1, radius); break; default: cout<< choice << " is a wrong choice "; void draw() for (int i=0;i<25;++i) images[i]->draw(); void main() figure myfigure; myfigure.draw(); Output of the Program Square is drawn at ( 27, ) and with length as 11 Triangle is drawn at ( 27, 0 ) ( 0, 30 ) ( , 0 ) Triangle is drawn at ( 27, 0 ) ( 48, 30 ) ( , 0 ) Square is drawn at ( 27, 0 ) and with length as 2 Circle is drawn at ( 27, 0 ) and the radius is 0 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Square is drawn at ( 27, 0 ) and with length as 13 Square is drawn at ( 27, 0 ) and with length as 17 Circle is drawn at ( 27, 0 ) and the radius is 4 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Square is drawn at ( 27, 0 ) and with length as 19 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Circle is drawn at ( 27, 0 ) and the radius is 5 Circle is drawn at ( 27, 0 ) and the radius is 2 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Circle is drawn at ( 27, 0 ) and the radius is 8 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Square is drawn at ( 27, 0 ) and with length as 15 Square is drawn at ( 27, 0 ) and with length as 5 Square is drawn at ( 27, 0 ) and with length as 4 Triangle is drawn at ( 27, 0 ) ( 48, 13 ) ( 2, 1 ) Circle is drawn at ( 27, 0 ) and the radius is 6
22 Pure Virtual Function When a class does not have any object, there is no need to have functions for it as there is no object to utilize those functions Consider a case of class Shape that we have discussed earlier We will never have an object of class Shape in actual working environment If we define draw() in the class, we will never be able to execute it It is important to understand that, because draw is a virtual function, we cannot have polymorphism without draw() defined in class Shape In other words, we need the definition of draw() in the Shape class but do not need the body. We can do the same by writing virtual void draw() // Empty The same can also be achieved by writing virtual void draw() = 0; Here, when we write = 0 in place of the function body, the function is said to be pure virtual function
23 Pure Virtual Function Pure virtual function has an important advantage It forces the native class to be abstract, and object of the class cannot be created. In a way, when a programmer wants the user not to define objects of a specific class, he can define a pure virtual function (may be a dummy) inside the class.
24 //PureVirtualFunction.cpp #include<iostream.h> using namespace std; class shape int linestyle, fillcollor; virtual void draw()=0; // this is pure virtual function virtual ~shape() cout << "Shape destroyed... "<<endl; ; void shape::draw() cout << "Shape is drawn \n"; class circle:public shape int radius, centerpointx, centerpointy; ~circle() cout<<"circle destroyed...\n"; void draw() cout << "Circle is drawn \n"; ; void main() // shape someshape; // error:cannot instantiate // abstract class shape *ptrshape; circle ring; // someshape.draw(); // not allowed ptrshape->shape::draw(); //static call to shape draw ptrshape = ˚ ptrshape->draw(); // this draws a circle cout <<" Messages from destructor starts now\n\n"; ptrshape = new circle; delete ptrshape; // if ~shape is not virtual, this won't // work as expected cout<<" Above messages are from delete \n\n"; cout<<"following messages are normal messages exiting the program\n"; Output of the program Shape is drawn Circle is drawn Messages from destructor starts now Circle destroyed... Shape destroyed... Above messages are from delete following messages are normal messages exiting the program Circle destroyed... Shape destroyed...
25 ?
Polymorphism 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 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 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 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 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 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 information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
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. 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 informationOOP THROUGH C++(R16) int *x; float *f; char *c;
What is pointer and how to declare it? Write the features of pointers? A pointer is a memory variable that stores the address of another variable. Pointer can have any name that is legal for other variables,
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 informationIUE Faculty of Engineering and Computer Sciences Spring Semester
IUE Faculty of Engineering and Computer Sciences 2010-2011 Spring Semester CS116 Introduction to Programming II Midterm Exam II (May 11 th, 2011) This exam document has 5 pages and 4 questions. The exam
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 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 informationObject Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year
Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures
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 informationModule 10 Inheritance, Virtual Functions, and Polymorphism
Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:
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 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 informationExtending Classes (contd.) (Chapter 15) Questions:
Extending Classes (contd.) (Chapter 15) Questions: 1 Virtual Functions in C++ Employee /\ / \ ---- Manager 2 Case 1: class Employee { string firstname, lastname; //... Employee( string fnam, string lnam
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 informationLecture 5: Inheritance
McGill University Computer Science Department COMP 322 : Introduction to C++ Winter 2009 Lecture 5: Inheritance Sami Zhioua March 11 th, 2009 1 Inheritance Inheritance is a form of software reusability
More informationCpt S 122 Data Structures. Course Review Midterm Exam # 2
Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm
More informationFriend Functions, Inheritance
Friend Functions, Inheritance Friend Function Private data member of a class can not be accessed by an object of another class Similarly protected data member function of a class can not be accessed by
More informationExtending Classes (contd.) (Chapter 15) Questions:
Extending Classes (contd.) (Chapter 15) Questions: 1 1. The following C++ program compiles without any problems. When run, it even prints out the hello called for in line (B) of main. But subsequently
More informationThe mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.
Class : BCA 3rd Semester Course Code: BCA-S3-03 Course Title: Object Oriented Programming Concepts in C++ Unit III Inheritance The mechanism that allows us to extend the definition of a class without making
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 informationCS250 Final Review Questions
CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand
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 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 informationPolymorphism. Arizona State University 1
Polymorphism CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 15 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University
More informationObject Oriented Software Design II
Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
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 Software Design II
Object Oriented Software Design II Inheritance Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 29, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February
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 informationC++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator
C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors
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. 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 informationOBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism http://en.wikipedia.org/wiki/encapsulation_(object-oriented_programming)
More informationJAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)
Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202
More informationTHE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.
Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically
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 informationCMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am
CMSC 202 Section 010x Spring 2007 Computer Science II Final Exam Name: Username: Score Max Section: (check one) 0101 - Justin Martineau, Tuesday 11:30am 0102 - Sandeep Balijepalli, Thursday 11:30am 0103
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 informationIS0020 Program Design and Software Tools Midterm, Fall, 2004
IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the
More informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationObject-Oriented Programming, Iouliia Skliarova
Object-Oriented Programming, Iouliia Skliarova You reuse code by creating new classes, but instead of creating them from scratch, you use existing classes that someone else has built and debugged. In composition
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 informationObject Oriented Programming in C++ Basics of OOP
Object Oriented Programming in C++ Basics of OOP In this section we describe the three most important areas in object oriented programming: encapsulation, inheritance and polymorphism. 1. INTRODUCTION
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationG52CPP C++ Programming Lecture 13
G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and
More informationA506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).
A506 / C201 Computer Programming II Placement Exam Sample Questions For each of the following, choose the most appropriate answer (2pts each). 1. Which of the following functions is causing a temporary
More informationGovernment Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING
Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++
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 informationG52CPP C++ Programming Lecture 14. Dr Jason Atkin
G52CPP C++ Programming Lecture 14 Dr Jason Atkin 1 Last Lecture Automatically created methods: A default constructor so that objects can be created without defining a constructor A copy constructor used
More informationIntro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.
Intro to OOP - Object and class - The sequence to define and use a class in a program - How/when to use scope resolution operator - How/when to the dot operator - Should be able to write the prototype
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 information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED - Polymorphism - Virtual Functions - Abstract Classes - Virtual
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 informationOBJECT ORIENTED PROGRAMMING
Classes and Objects So far you have explored the structure of a simple program that starts execution at main() and enables you to declare local and global variables and constants and branch your execution
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 informationCSCE 110 PROGRAMMING FUNDAMENTALS
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table
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 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 informationSTRUCTURING OF PROGRAM
Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the
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 informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationRecharge (int, int, int); //constructor declared void disply();
Constructor and destructors in C++ Constructor Constructor is a special member function of the class which is invoked automatically when new object is created. The purpose of constructor is to initialize
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 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 informationConstructor - example
Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever
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 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 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 informationUse the dot operator to access a member of a specific object.
Lab 16 Class A class is a data type that can contain several parts, which are called members. There are two types of members, data member and functions. An object is an instance of a class, and each object
More informationCSCI 102L - Data Structures Midterm Exam #1 Fall 2011
Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
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 informationC++ 8. Constructors and Destructors
8. Constructors and Destructors C++ 1. When an instance of a class comes into scope, the function that executed is. a) Destructors b) Constructors c) Inline d) Friend 2. When a class object goes out of
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 informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Multiple Inheritance July 26, 2004 22.9 Multiple Inheritance 2 Multiple inheritance Derived class has several base classes Powerful,
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationCOEN244: Polymorphism
COEN244: Polymorphism Aishy Amer Electrical & Computer Engineering Polymorphism means variable behavior / ability to appear in many forms Outline Casting between objects Using pointers to access objects
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 informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
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 informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationOOP. Unit:3.3 Inheritance
Unit:3.3 Inheritance Inheritance is like a child inheriting the features of its parents. It is a technique of organizing information in a hierarchical (tree) form. Inheritance allows new classes to be
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 informationIntroduction to Programming
Introduction to Programming SS 2010 Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 Stand: June 21, 2010 Betriebssysteme / verteilte Systeme Introduction
More informationObject oriented programming
Exercises 12 Version 1.0, 9 May, 2017 Table of Contents 1. Virtual destructor and example problems...................................... 1 1.1. Virtual destructor.......................................................
More informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationC++_ MARKS 40 MIN
C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float
More informationKLiC C++ Programming. (KLiC Certificate in C++ Programming)
KLiC C++ Programming (KLiC Certificate in C++ Programming) Turbo C Skills: Pre-requisite Knowledge and Skills, Inspire with C Programming, Checklist for Installation, The Programming Languages, The main
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationCSCI 102 Fall 2010 Exam #1
Name: USC Username: CSCI 102 Fall 2010 Exam #1 Problems Problem #1 (14 points) Problem #2 (15 points) Problem #3 (20 points) Problem #4 (16 points) Problem #5 (35 points) Total (100 points) Problem 1 Short
More informationExample : class Student { int rollno; float marks; public: student( ) //Constructor { rollno=0; marks=0.0; } //other public members };
Constructors A Member function with the same name as its classis called Constructor and it is used to initilize the objects of that class type with a legal value. A Constructor is a special member function
More informationChapter 15: Inheritance, Polymorphism, and Virtual Functions
Chapter 15: Inheritance, Polymorphism, and Virtual Functions 15.1 What Is Inheritance? What Is Inheritance? Provides a way to create a new class from an existing class The new class is a specialized version
More information