CS OBJECT ORIENTED PROGRAMMING

Size: px
Start display at page:

Download "CS OBJECT ORIENTED PROGRAMMING"

Transcription

1 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 functions pure virtual functions RTTI typeid dynamic casting RTTI and templates cross casting down casting. 1. Explain different types of inheritance in c++ with example programs. (16) Inheritance is a concept of linking two or more classes with each other in a hierarchical manner so that their properties and functions can be shared. (One class will extend to another class.) This leads to the biggest advantage of re-usability of the members and avoids redundancy. Inheritance leads to various issues such as: What is Inherited types of inheritance accessibility modes (public, private and protected) in inheritance Friend function and inheritance etc. Single Inheritance: #include<conio.h> #include <iostream> using namespace std; class Person private: string name; string sex; int age; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 1

2 void ReadData() cout<<"name:"; cin>>name; cout<<"sex:"; cin>>sex; cout<<"age:"; cin>>age; void display() cout<<"name:"<<name<<endl; cout<<"sex:"<<sex<<endl; cout<<"age:"<<age<<endl; ; class student:public Person private: int rollno; string branch; void ReadData() Person::ReadData(); cout<<"roll No:"; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 2

3 cin>>rollno; cout<<"branch:"; cin>>branch; void display() Person::display(); cout<<"roll No:"<<rollno<<endl; cout<<"branch:"<<branch<<endl; ; int main() student s1; s1.readdata(); s1.display(); getch(); Output: Name:Mike Sex:Male Age:32 Roll No:1320 Branch:CSE Name:Mike Sex:Male Age:32 L. Maria Michael Visuwasam, A.P, CSE, VIT Page 3

4 Roll No:1320 Branch:CSE Hierarchical Inheritance: #include <iostream> using namespace std; class Cpolygon protected: int width, height; void input_values (int one, int two) width=one; height=two; ; class Crectangle: public Cpolygon int area () return (width * height); ; class Ctriangle: public Cpolygon L. Maria Michael Visuwasam, A.P, CSE, VIT Page 4

5 int area () return (width * height / 2); ; int main () Crectangle rectangle; Ctriangle triangle; rectangle.input_values (2,2); triangle.input_values (2,2); cout << rectangle.area() << endl; cout << triangle.area() << endl; return 0; In the example above we have used the protected members of the class Cpolygon in the class Crectangle and in the Ctriangle class. This is only possible through Inheritance. What is inherited? When inheritance is done, various links and tables (index, virtual etc) are created which are used to provide the accessibility of the members of the base class in derived class and in other class hierarchy. This means saying public members are inherited is better to say as public members become accessible. A derived class inherits every member of a base class except: its constructor and its destructor its friends its operator=() members L. Maria Michael Visuwasam, A.P, CSE, VIT Page 5

6 Types of Inheritance There are five different inheritances supported in C++: (1) Simple / Single (2) Multilevel (3) Hierarchical (4) Multiple (5) Hybrid Types of Inheritance flow chart Multiple Inheritance Multiple inheritance is achieved whenever more than one class acts as base classes for other classes. This makes the members of the base classes accessible in the derived class, resulting in better integration and broader re-usability. Take a look at an example: #include <iostream> using namespace std; class Cpolygon protected: int width, height; void input_values (int one, int two) L. Maria Michael Visuwasam, A.P, CSE, VIT Page 6

7 width=one; height=two; ; class Cprint void printing (int output); ; void Cprint::printing (int output) cout << output << endl; class Crectangle: public Cpolygon, public Cprint int area () return (width * height); ; class Ctriangle: public Cpolygon, public Cprint int area () L. Maria Michael Visuwasam, A.P, CSE, VIT Page 7

8 return (width * height / 2); ; int main () Crectangle rectangle; Ctriangle triangle; rectangle.input_values (2,2); triangle.input_values (2,2); rectangle.printing (rectangle.area()); triangle.printing (triangle.area()); return 0; Note:the two public statements in the Crectangle class and Ctriangle class. Accessibility modes and Inheritance We can use the following chart for seeing the accessibility of the members in the Base class (first class) and derived class (second class). Accessibility modes inheritance chart Here X indicates that the members are not inherited, i.e. they are not accessible in the derived class. L. Maria Michael Visuwasam, A.P, CSE, VIT Page 8

9 2. Write a program to print the internal and external marks. And print the total marks using multiple inheritance. And also find out the grade in each subject and print the class. Use appropriate access specifiers and methods to access the data s. (16) //Multiple Inheritance #include<conio.h> #include <iostream> using namespace std; class InternalExam protected: int sub1marks; int sub2marks; void ReadData() cout<<"marks scored in Subject-1:"; cin>>sub1marks; cout<<"marks scored in Subject-2:"; cin>>sub2marks; void display() cout<<"internal Marks scored in Subject-1:"<<sub1marks<<endl; cout<<"internal Marks scored in Subject-2:"<<sub2marks<<endl; ; class ExternalExam L. Maria Michael Visuwasam, A.P, CSE, VIT Page 9

10 protected: int sub1marks; int sub2marks; void ReadData() cout<<"marks scored in Subject-1:"; cin>>sub1marks; cout<<"marks scored in subject-2:"; cin>>sub2marks; void display() cout<<"external Marks scored in Subject-1:"<<sub1marks<<endl; cout<<"external Marks scored in Subject-2:"<<sub2marks<<endl; ; class Result:public InternalExam, public ExternalExam private: int sub1total; int sub2total; void ReadData() cout<<"**********enter Internal Exam Marks*********"<<endl; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 10

11 InternalExam::ReadData(); cout<<"**********enter External Exam Marks*********"<<endl; ExternalExam::ReadData(); void Totalmarks() sub1total=internalexam::sub1marks+externalexam::sub1marks; sub2total=internalexam::sub2marks+externalexam::sub2marks; void display() InternalExam::display(); ExternalExam::display(); cout<<"**********************************"<<endl; double average=((sub1total+sub2total)/2)*100; cout<<"\n subject1 Marks:"<<sub1total<< \t ; if(sub1total>50 && sub1total<60) cout<<"e Grade"<<endl; if(sub1total>61 && sub1total<=70) cout<<"c Grade"<<endl; if(sub1total>71 && sub1total<=80) cout<<"b Grade"<<endl; if(sub1total>81 && sub1total<=90) cout<<"a Grade"<<endl; if(sub1total>91 && sub1total<=100) cout<<"s Grade"<<endl; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 11

12 cout<<"\n subject2 Marks:"<<sub2total<< \t ; if(sub1total>50 && sub1total<60) cout<<"e Grade"<<endl; if(sub2total>61 && sub2total<=70) cout<<"c Grade"<<endl; if(sub2total>71 && sub2total<=80) cout<<"b Grade"<<endl; if(sub2total>81 && sub2total<=90) cout<<"a Grade"<<endl; if(sub2total>91 && sub2total<=100) cout<<"c Grade"<<endl; cout<<"*********************grade *****************"<<endl; if(average>=85) cout<<"distinction"; ; int main() Result r1; r1.readdata(); r1.totalmarks(); r1.display(); getch(); Output: **********Enter Internal Exam Marks********* Marks scored in Subject-1:18 L. Maria Michael Visuwasam, A.P, CSE, VIT Page 12

13 Marks scored in Subject-2:19 **********Enter External Exam Marks********* Marks scored in Subject-1:75 Marks scored in subject-2:70 Internal Marks scored in Subject-1:18 Internal Marks scored in Subject-2:19 External Marks scored in Subject-1:75 External Marks scored in Subject-2:70 ********************************** subject1 Marks:93 subject2 Marks:89 S Grade A Grade *********************GRADE ***************** Distinction 3. Explain the use of virtual base class with a simple program. (8) An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class. C++ solves this issue by introducing a virtual base class. When a class is made virtual, is taken so that the duplication is avoided regardless of the number of paths that exist to the child class. When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class name with the word virtual. Example: //virtual base class #include <conio.h> #include <iostream> L. Maria Michael Visuwasam, A.P, CSE, VIT Page 13

14 using namespace std; class Baseclass string p; void display() cout<<p<<"\t"; ; class Derivedclass1:virtual public Baseclass //virtual base class string q; void display() Baseclass::display(); cout<<q<<"\t"; ; class Derivedclass2:virtual public Baseclass // virtual base class L. Maria Michael Visuwasam, A.P, CSE, VIT Page 14

15 string r; void display() cout<<r; ; class Derivedclass3:public Derivedclass1, public Derivedclass2 string s; void display() Derivedclass1::display(); Derivedclass2::display(); cout<<s; ; int main() Derivedclass3 d3; d3.p="maria"; d3.q="michael"; d3.r="visuwasam"; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 15

16 d3.s=".l"; d3.display(); getch(); Output maria michael visuwasam.l 4. Explain abstract class with a suitable example. (8) An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation detail separate from associated data. A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows: class Box // pure virtaul function virtual double getvolume() = 0; private: double length; double breadth; double height; // Length of a box // Breadth of a box // Height of a box ; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 16

17 The purpose of an abstract class (often referred to as an ABC) is to provide an appropriate base class from which other classes can inherit. Abstract classes cannot be used to instantiate objects and serves only as an interface. Attempting to instantiate an object of an abstract class causes a compilation error. Thus, if a subclass of an ABC needs to be instantiated, it has to implement each of the virtual functions, which means that it supports the interface declared by the ABC. Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error. Classes that can be used to instantiate objects are called concrete classes. Abstract Class Example: Consider the following example where parent class provides an interface to the base class to implement a function called getarea(): #include <iostream> using namespace std; // Base class class Shape // pure virtual function providing interface framework. virtual int getarea() = 0; void setwidth(int w) width = w; void setheight(int h) height = h; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 17

18 protected: int width; int height; ; // Derived classes class Rectangle: public Shape int getarea() return (width * height); ; class Triangle: public Shape int getarea() return (width * height)/2; ; int main(void) L. Maria Michael Visuwasam, A.P, CSE, VIT Page 18

19 Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; When the above code is compiled and executed, it produces following result: Total Rectangle area: 35 Total Triangle area: 17 You can see how an abstract class defined an interface in terms of getarea() and two other classes implemented same function but with different algorithm to calculate the area specific to the shape. Designing Strategy: An object-oriented system might use an abstract base class to provide a common and standarized interface appropriate for all the external applications. Then, through inheritance from that abstract base class, derived classes are formed that all operate similarly. The capabilities (i.e., the public functions) offered by the external applications are provided as pure virtual functions in the abstract base class. The implementations L. Maria Michael Visuwasam, A.P, CSE, VIT Page 19

20 of these pure virtual functions are provided in the derived classes that correspond to the specific types of the application. This architecture also allows new applications to be added to a system easily, even after the system has been defined. 5. What is the use of Virtual functions and the rules for virtual function? Give an appropriate example. And also give the syntax for the pure virtual functions. (10) (Or) Explain how run time polymorphism can be achieved using virtual functions. A virtual function is a function in a base class that is declared using the keyword virtual. Defining in a base class a virtual function, with another version in a derived class, signals to the compiler that we don't want static linkage for this function. What we do want is the selection of the function to be called at any given point in the program to be based on the kind of object for which it is called. This sort of operation is referred to as dynamic linkage, or late binding. Rules for virtual functions: The virtual functions must be preceded by virtual keyword in the base class. 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. The function in the derived class need not be preceded by virtual keyword. If it is preceded by virtual keyword, it makes no difference. If a function with the same name is not defined in the derived class, the original base class function is invoked. The virtual function must be defined in the base class; however it may have an empty body. To use virtual function, a class hierarchy should be present. The constructor function cannot be virtual. The virtual function cannot be a static member. They are accessed using object pointers. Example: Consider the following example where a base class has been derived by other two classes: #include <iostream> L. Maria Michael Visuwasam, A.P, CSE, VIT Page 20

21 using namespace std; class Shape protected: int width, height; Shape( int a=0, int b=0) width = a; height = b; int area() cout << "Parent class area :" <<endl; return 0; ; class Rectangle: public Shape Rectangle( int a=0, int b=0) Shape(a, b); int area () L. Maria Michael Visuwasam, A.P, CSE, VIT Page 21

22 cout << "Rectangle class area :" <<endl; return (width * height); ; class Triangle: public Shape Triangle( int a=0, int b=0) Shape(a, b); int area () cout << "Rectangle class area :" <<endl; return (width * height / 2); ; // Main function for the program int main( ) Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); L. Maria Michael Visuwasam, A.P, CSE, VIT Page 22

23 // store the address of Rectangle shape = &rec; // call rectangle area. shape->area(); // store the address of Triangle shape = &tri; // call triangle area. shape->area(); return 0; When the above code is compiled and executed, it produces following result: Parent class area Parent class area The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program. But now, let's make a slight modification in our program and precede the declaration of area() in the Shape class with the keyword virtual so that it looks like this: class Shape protected: int width, height; Shape( int a=0, int b=0) L. Maria Michael Visuwasam, A.P, CSE, VIT Page 23

24 width = a; height = b; virtual int area() cout << "Parent class area :" <<endl; return 0; ; After this slight modification, when the previous example code is compiled and executed, it produces following result: Output: Rectangle class area Triangle class area This time the compiler looks at the contents of the pointer instead of it's type. Hence since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called. As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations. Pure Virtual Functions: It's possible that you'd want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. We can change the virtual function area() in the base class to the following: class Shape protected: L. Maria Michael Visuwasam, A.P, CSE, VIT Page 24

25 ; int width, height; Shape( int a=0, int b=0) width = a; height = b; // pure virtual function virtual int area() = 0; The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function. 6. Explain all types of casting using c++ with example programs. (16) Casting operators used in c++ dynamic_cast The dynamic_cast is a casting operator. The following are salient features of dynamic_cast The casting operator is used only for polymorphic object casting. That means it is possible to cast from one polymorphic object to another polymorphic object. dynamic_cast is also known as safe cast. It succeeds only when properly it is casted. The syntax of dynamic_cast is dynamic_cast<toobject or reference>(from object or reference) Casting from derived class pointer object to base class pointer object always succeeds. But the casting from base class pointer object to derived class pointer object succeeds only if base pointer is actually pointing to an object of derived type. The casting is done with pointers or reference only. It cannot be done with objects. In cases of pointers, it is important to check the return value of the dynamic_cast to know if the cast is successful. In cases of references, the reference cannot be null, so dynamic_cast will throw bad_cast when it fails. Polymorphic objects can be dynamically casted using dynamic_cast. L. Maria Michael Visuwasam, A.P, CSE, VIT Page 25

26 Example: If a class is polymorphic then dynamic_cast will perform a special check during execution. This check ensures that the expression is a valid and complete object of the requested class. Take a look at the example: // dynamic_cast #include <iostream> #include <exception> using namespace std; class Base_Class virtual void dummy() ; class Derived_Class: public Base_Class int a; ; int main () try return 0; Base_Class * ptr_a = new Derived_Class; Base_Class * ptr_b = new Base_Class; Derived_Class * ptr_c; ptr_c = dynamic_cast< Derived_Class *>(ptr_a); if (ptr_c ==0) cout << "Null pointer on first type-cast" << endl; ptr_c = dynamic_cast< Derived_Class *>(ptr_b); if (ptr_c ==0) cout << "Null pointer on second type-cast" << endl; catch (exception& my_ex) cout << "Exception: " << my_ex.what(); In the example we perform two dynamic_casts from pointer objects of type Base_Class* (namely ptr_a and ptr_b) to a pointer object of type Derived_Class*. If everything goes well then the first one should be successful and the second one will fail. The pointers ptr_a and ptr_b are both of the type Base_Class. The pointer ptr_a points to an object of the type Derived_Class. The pointer ptr_b points to an object of the type Base_Class. So when the dynamic type cast is performed then ptr_a is pointing to a full L. Maria Michael Visuwasam, A.P, CSE, VIT Page 26

27 object of class Derived_Class, but the pointer ptr_b points to an object of class Base_Class. This object is an incomplete object of class Derived_Class; thus this cast will fail! Because this dynamic_cast fails a null pointer is returned to indicate a failure. When a reference type is converted with dynamic_cast and the conversion fails then there will be an exception thrown out instead of the null pointer. The exception will be of the type bad_cast. With dynamic_cast it is also possible to cast null pointers even between the pointers of unrelated classes. Dynamic_cast can cast pointers of any type to void pointer(void*). const_cast: This type of casting manipulates the constness of an object, either to be set or to be removed. For example, in order to pass a const argument to a function that expects a non-constant parameter. // const_cast #include <iostream> using namespace std; void print (char * str) cout << str << endl; int main () const char * c = "sample text"; print ( const_cast<char *> (c) ); return 0; Output: Sample text static_cast: static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided. #include <iostream> #include <typeinfo> using namespace std; void main() L. Maria Michael Visuwasam, A.P, CSE, VIT Page 27

28 char c= a ; int a=static_cast<int>(c); cout<<a; Output: 97 reinterpret_cast The reinterpret_cast is a casting operator which is used to convert to an irrelevant type like converting an integer value to a pointer. #include <iostream> #include <typeinfo> using namespace std; void main() int normalint=100; int *pointerint=reinterpret_cast<int*>(normalint); cout<<pointerint; CROSS CASTING In multiple inheritance, when a derived class object is pointed by one of its base class pointer object, casting from one base class pointer into another base class pointer is known as cross casting. This is done by using dynamic_cast in multiple inheritances. //CROSS CASTING #include <iostream> #include <typeinfo> #include <conio.h> using namespace std; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 28

29 class Baseclass1 virtual ~Baseclass1() virtual void show() cout<<"base class 1"<<endl; ; class Baseclass2 int a; virtual void show() cout<<"base class 2"<<endl; ; class Derivedclass:public Baseclass1,public Baseclass2 int x; virtual void show() cout<<"derived class "<<endl; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 29

30 ; int main() Baseclass1 *base1ptr=new Derivedclass; Baseclass2 *base2ptr=dynamic_cast<baseclass2*>(base1ptr); //call from base1ptr to base2ptr //baseptr base1ptr->show(); Baseclass1 *baseptr; Baseclass2 b2; //baseptr=&b2; baseptr->show(); getch(); Output: Derived class Down Casting: Casting from base class pointer to the derived class pointer is known as down casting. //Downcasting #include <conio.h> #include <iostream> #include <typeinfo> using namespace std; class Shape L. Maria Michael Visuwasam, A.P, CSE, VIT Page 30

31 virtual void show() ; class Circle:public Shape ; cout<<"shape is drawn"<<endl; void show() int main() cout<<"circle is drawn"<<endl; Shape *ptrshape, sh; Circle *ptrcircle, c; c.show(); ptrshape=&c; ptrshape->show(); ptrcircle=dynamic_cast<circle*>(ptrshape); //casting from base class ptr to derived class ptr ptrcircle->show(); getch(); Output: Circle is drawn Circle is drawn Circle is drawn L. Maria Michael Visuwasam, A.P, CSE, VIT Page 31

32 7. Explain briefly about the role of RTTI and typeid in c++. (8) RTTI: Real time information is a mechanism by which we can find the type of an object at run time. In other words, it allows programs that use pointer or reference to base classes to retrieve the actual derived types of the objects to which these pointers or references refer. When we define virtual functions in the base class, they can solve problems of the entire class hierarchy. When we need to solve problems related to some portions of the hierarchy we cannot directly solve it. It is better to use typeid with RTTI in this case. RTTI is provided through two operators: The typeid operator which returns the actual type of the object referred to by a pointer or a reference. The dynamic_cast operator, which safely converts from a pointer or reference to a base type to a pointer or reference of derived type. typeid typeid allows to check the type of an expression: typeid (expression) This operator returns a reference to a constant object of type type_info that is defined in the standard header file<typeinfo>. This returned value can be compared with another one using operators == and!= or can serve to obtain a null-terminated character sequence representing the data type or class name by using its name() member. // typeid #include <iostream> #include <typeinfo> using namespace std; int main () int * a,b; a=0; b=0; if (typeid(a)!= typeid(b)) cout << "a and b are of different types:\n"; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; L. Maria Michael Visuwasam, A.P, CSE, VIT Page 32

33 return 0; Output: a and b are of different types: a is: int * b is: int When typeid is applied to classes typeid uses the RTTI to keep track of the type of dynamic objects. When typeid is applied to an expression whose type is a polymorphic class, the result is the type of the most derived complete object: // typeid, polymorphic class #include <iostream> #include <typeinfo> #include <exception> using namespace std; class CBase virtual void f() ; class CDerived : public CBase ; int main () try CBase* a = new CBase; CBase* b = new CDerived; cout << "a is: " << typeid(a).name() << '\n'; cout << "b is: " << typeid(b).name() << '\n'; cout << "*a is: " << typeid(*a).name() << '\n'; cout << "*b is: " << typeid(*b).name() << '\n'; catch (exception& e) cout << "Exception: " << e.what() << endl; return 0; Output: a is: class CBase * b is: class CBase * *a is: class CBase *b is: class CDerived L. Maria Michael Visuwasam, A.P, CSE, VIT Page 33

Dr. Md. Humayun Kabir CSE Department, BUET

Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Dr. Md. Humayun Kabir CSE Department, BUET C++ Type Casting Converting a value of a given type into another type is known as type-casting. ti Conversion can be implicit or explicit 2 C++

More information

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

UNIVERSITI 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 information

Friend Functions, Inheritance

Friend 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 information

Inheritance

Inheritance Inheritance 23-01-2016 Inheritance Inheritance is the capability of one class to acquire properties and characteristics from another class. For using Inheritance concept in our program we must use at least

More information

Inheritance, and Polymorphism.

Inheritance, 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 information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 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 information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt 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 information

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

JAYARAM 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 information

Increases Program Structure which results in greater reliability. Polymorphism

Increases 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 information

Polymorphism Part 1 1

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 information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 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 information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 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 information

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Jayaram 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 information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

ECE 3574: Dynamic Polymorphism using Inheritance

ECE 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 information

The mechanism that allows us to extend the definition of a class without making any physical changes to the existing class is called inheritance.

The 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 information

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std;

21. Exceptions. Advanced Concepts: // exceptions #include <iostream> using namespace std; - 147 - Advanced Concepts: 21. Exceptions Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers.

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What 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 information

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

Polymorphism. 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 information

Polymorphism. Zimmer CSCI 330

Polymorphism. 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 information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C 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 information

UNIT - IV INHERITANCE AND FORMATTED I/O

UNIT - IV INHERITANCE AND FORMATTED I/O UNIT - IV INHERITANCE AND FORMATTED I/O CONTENTS: Inheritance Public, private and protected derivations Multiple inheritance Virtual base class Abstract class Composite objects Runtime polymorphism\ Virtual

More information

C++ Programming: Polymorphism

C++ 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 information

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. C++ TEMPLATES http://www.tutorialspoint.com/cplusplus/cpp_templates.htm Copyright tutorialspoint.com Templates are the foundation of generic programming, which involves writing code in a way that is independent

More information

CPSC 427: Object-Oriented Programming

CPSC 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 information

UNIT 1 OVERVIEW LECTURE NOTES

UNIT 1 OVERVIEW LECTURE NOTES UNIT 1 OVERVIEW LECTURE NOTES OBJECT-ORIENTED PROGRAMMING IN C++ Object Oriented Programming is a method of visualizing and programming the problem in a global way. Object oriented programming is a technique

More information

POLYMORPHISM. Phone : (02668) , URL :

POLYMORPHISM. 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 information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT 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 information

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Introduction 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 information

18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std;

18. Polymorphism. Object Oriented Programming: Pointers to base class // pointers to base class #include <iostream> using namespace std; - 126 - Object Oriented Programming: 18. Polymorphism Before getting into this section, it is recommended that you have a proper understanding of pointers and class inheritance. If any of the following

More information

C++ Casts and Run-Time Type Identification

C++ Casts and Run-Time Type Identification APPENDIX K C++ Casts and Run-Time Type Identification Introduction There are many times when a programmer needs to use type casts to tell the compiler to convert the type of an expression to another type.

More information

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p. Preface to the Second Edition p. iii Preface to the First Edition p. vi Brief Contents p. ix Introduction to C++ p. 1 A Review of Structures p. 1 The Need for Structures p. 1 Creating a New Data Type Using

More information

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ 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 information

Lecture 5: Inheritance

Lecture 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 information

W3101: Programming Languages C++ Ramana Isukapalli

W3101: Programming Languages C++ Ramana Isukapalli Lecture-6 Operator overloading Namespaces Standard template library vector List Map Set Casting in C++ Operator Overloading Operator overloading On two objects of the same class, can we perform typical

More information

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns This Advanced C++ Programming training course is a comprehensive course consists of three modules. A preliminary module reviews

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

OOP THROUGH C++(R16) int *x; float *f; char *c;

OOP 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 information

CMSC 202 Section 010x Spring Justin Martineau, Tuesday 11:30am

CMSC 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 information

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Intro 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 information

TPF Users Group Spring 2005

TPF Users Group Spring 2005 TPF Users Group Spring 2005 Get Ready For Standard C++! Name : Edwin W. van de Grift Venue : Applications Development Subcommittee AIM Enterprise Platform Software IBM z/transaction Processing Facility

More information

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

More information

Object Oriented Programming with c++ Question Bank

Object Oriented Programming with c++ Question Bank Object Oriented Programming with c++ Question Bank UNIT-1: Introduction to C++ 1. Describe the following characteristics of OOP. i Encapsulation ii Polymorphism, iii Inheritance 2. Discuss function prototyping,

More information

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Overview of C++ Overloading Overloading occurs when the same operator or function name is used with different signatures Both operators and functions can be overloaded

More information

Data 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:

Data 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 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 엄현상 (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 information

CPSC 427: Object-Oriented Programming

CPSC 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 information

Programming in C++: Assignment Week 6

Programming 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 information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

RAJIV 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 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 information

Chapter 1: Object-Oriented Programming Using C++

Chapter 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

Extending Classes (contd.) (Chapter 15) Questions:

Extending 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 information

C++ 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 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 information

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2

OBJ. ORI.& MULT. PROG., M.C.Q. BANK, FOR UNIT -2, SECOND YEAR COMP. ENGG. SEM-4, 2012 PATTERN, U.O.P. UNIT-2 UNIT-2 Syllabus for Unit-2 Introduction, Need of operator overloading, overloading the assignment, binary and unary operators, overloading using friends, rules for operator overloading, type conversions

More information

Instantiation of Template class

Instantiation 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 information

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Inheritance. 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 information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Extending Classes (contd.) (Chapter 15) Questions:

Extending 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 information

Polymorphism. Arizona State University 1

Polymorphism. 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 information

Midterm Exam 5 April 20, 2015

Midterm 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 information

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts.

These new operators are intended to remove some of the holes in the C type system introduced by the old C-style casts. asting in C++: Bringing Safety and Smartness to Your Programs of 10 10/5/2009 1:20 PM By G. Bowden Wise The new C++ standard is full of powerful additions to the language: templates, run-time type identification

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government 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 information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Inheritance, Polymorphism and the Object Memory Model

Inheritance, Polymorphism and the Object Memory Model Inheritance, Polymorphism and the Object Memory Model 1 how objects are stored in memory at runtime? compiler - operations such as access to a member of an object are compiled runtime - implementation

More information

Object Oriented Programming. Solved MCQs - Part 2

Object 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 information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object 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 information

Absolute C++ Walter Savitch

Absolute 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 information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

Chapter 5. Object- Oriented Programming Part I

Chapter 5. Object- Oriented Programming Part I Chapter 5 Object- Oriented Programming Part I 5: Preview basic terminology comparison of the Java and C++ approaches to polymorphic programming techniques introduced before in the context of inheritance:

More information

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini marco.bertini@unifi.it http://www.micc.unifi.it/bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

VII. POLYMORPHISM AND VIRTUAL FUNCTIONS

VII. POLYMORPHISM AND VIRTUAL FUNCTIONS VII. POLYMORPHISM AND VIRTUAL FUNCTIONS VII.1 Early binding and late binding The concept of polymorphism enables different types of objects (in the same hierarchy) to use their own realization of the same

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini Laboratorio di Tecnologie dell'informazione Ing. Marco Bertini bertini@dsi.unifi.it http://www.dsi.unifi.it/~bertini/ Const correctness What is const correctness? It is a semantic constraint, enforced

More information

COEN244: Polymorphism

COEN244: 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 information

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction

More information

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

Note 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 information

C++_ MARKS 40 MIN

C++_ 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 information

CS105 C++ Lecture 7. More on Classes, Inheritance

CS105 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 information

STRUCTURING OF PROGRAM

STRUCTURING 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 information

Polymorphism CSCI 201 Principles of Software Development

Polymorphism 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 information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Inheritance: Single level inheritance:

Inheritance: Single level inheritance: Inheritance: The mechanism of deriving a new class from old one is called inheritance. The old class is referred to as the base class or parent class and the new class is called the derived class or child

More information

COMP322 - Introduction to C++

COMP322 - Introduction to C++ COMP322 - Introduction to C++ Winter 2011 Lecture 08 - Inheritance continued School of Computer Science McGill University March 8, 2011 Last Time Single Inheritance Polymorphism: Static Binding vs Dynamic

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 Introduction 2 IS 0020 Program Design and Software Tools Exception Handling Lecture 12 November 23, 200 Exceptions Indicates problem occurred in program Not common An "exception" to a program that usually

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL 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 information

Object 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: 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 information

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued COMP322 - Introduction to C++ Lecture 09 - Inheritance continued Dan Pomerantz School of Computer Science 11 March 2012 Recall from last time Inheritance describes the creation of derived classes from

More information

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.

Classes: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods. Classes: Methods, Constructors, Destructors and Assignment For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Classes: Member functions // classes

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

This examination has 11 pages. Check that you have a complete paper.

This examination has 11 pages. Check that you have a complete paper. MARKING KEY The University of British Columbia MARKING KEY Computer Science 252 2nd Midterm Exam 6:30 PM, Monday, November 8, 2004 Instructors: K. Booth & N. Hutchinson Time: 90 minutes Total marks: 90

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 (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 information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Course Title: Object Oriented Programming Full Marks: 60 20 20 Course No: CSC161 Pass Marks: 24 8 8 Nature of Course: Theory Lab Credit Hrs: 3 Semester: II Course Description:

More information

SSE2034: System Software Experiment 3 Spring 2016

SSE2034: System Software Experiment 3 Spring 2016 SSE2034: System Software Experiment 3 Spring 2016 Jinkyu Jeong ( jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu Object Initialization class Rectangle { private:

More information

Example Final Questions Instructions

Example Final Questions Instructions Example Final Questions Instructions This exam paper contains a set of sample final exam questions. It is for practice purposes only. You ll most likely need longer than three hours to answer all the questions.

More information

Lecture 6. Inheritance

Lecture 6. Inheritance Inheritance Lecture 6 A key feature of C++ classes is inheritance. Inheritance allows to create classes which are derived from other classes, so that they automatically include some of its "parent's" members,

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Fast Introduction to Object Oriented Programming and C++

Fast 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 information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information