Instantiation of Template class

Size: px
Start display at page:

Download "Instantiation of Template class"

Transcription

1 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 Until compilers and linkers are integrated better, the template classes definitions as well as code are placed in header file. You include a template file (i.e. header file) in your source program. You should never compile a template file alone. member functions must be template functions. 800

2 An example template <class T1, class T2> class SomeNewClass { public: SomeNewClass(const T1& t1); ~SomeNewClass(); T1& SetData(const T2& t2, int n); : private: T1 a; T2 b; } Code for all functions are placed here. 801

3 Instantiation of Template class #include <somenewclass.h> int main() { SomeNewClass<int,double> x; SomeNewClass<string,int> y; : : } Compiler will create automatically two sets for functions based on the template code. 802

4 Template List Class template <class ListItem> class List { public: List(); ~List(); bool IsEmpty(); void Insert(int pos, const ListItem& item, bool& success); void Delete(int pos, bool& success); : : 803

5 Template List Class (contd) private: struct ListNode; typedef ListNode* ListNodePtr; struct ListNode { ListItem item; ListNodePtr next; }; } ListNodePtr head; int size; 804

6 Template List Class (contd) template <class ListItem> List<ListItem>::List() { : } template <class ListItem> List<ListItem>::Insert(int pos, const ListItem& item, bool& success) { : } 805

7 Operator Overloading Standard Operators in C++ can be overloaded to have a different meaning when applied to operands of a new user defined class. The associativity or precedence of the operators remain the same. Operators such as + - * / = == < <= > >= & [] e.t.c. are all candidates for overloading. When overloading these operators we should maintain the intuitive meaning of these operators. We should also try to be consistent with their usage on built-in types. a + b does not change a or b. a = b, changes a but not b. It has value so that we can do c = a = b; 806

8 Operators as member functions If you define an operator using a member function, then the left operand must be an object of the class for which the overloading is done. Operator funtions can be overloaded. e.g. Complex a,b,c; c = a + b; is same as c = a.operator+(b); which in turn is same as c.operator=(a.operator+(b)); Will c = a + 2 work? Yes!! if Complex class has a constructor that takes an integer as parameter. Compiler will create a temporary object using this constructor and add with a. Then the temporary object is destroyed. Thus, there is implicit casting done on rhs. 807

9 Operator as member function Will c = 2 + a work? No!! Compiler will not cast 2 into Complex obj. Casting is done only for function parameters, not for the implicit object. When you define a operator as member function, the lhs operand MUST be an obj of the class. The type of rhs operand can be anything as long as you provide an operator function that takes that type or else there is a constructor function. Casting is done only if it can t find a matching function. It is not a good idea to depend on casting. If there is more than one way to cast, it leads to confusion. 808

10 Operator as non-member function It is also possible to define the operator functions as non-member functions. Non-member function do not have implicit operand. Both operands are passed. Both operands are defined as const ref parameters. Non-member function can t access private variables of the class, unless it is defined as friend function inside the class (prototype). If non-member function is defined as friend, it serves as the prototype or else give an explicit prototype anyway. Avoid friend functions as much as possible. 809

11 Operator as non-member function With non-member function operator+ will the following work? Complex a,b; b = 2 + a; Yes!! 2 will be cast as Complex object by compiler Non-member function is preferable to member functions when defining operators. Provide sufficient access functions in the class so that there is no need to give friend status to the function. 810

12 Operator Overloading (contd) class Foo { public: : bool operator<(const Foo& rhs) const; Foo operator+(const Foo& rhs) const; Foo& operator=(const Foo& rhs); bool operator==(const Foo& rhs) const; : } Note the use of const as necessary in defining the operator functions. For templates, Foo becomes, say Foo<T>. 811

13 operator = The left hand side operand is the implicit object. The left-hand side object is assigned the value of right hand side object. The code for operator= should first check for selfassignment. The code should also free the existing values for left hand side object before copying rhs. The return value should be a reference to the left hand side object (which is implicit). This can be done by return(*this). The right hand side object should not change and hence is a const parameter. 812

14 Operator + + means addition for numbers. + can mean concatenation for strings. + can mean Union for sets. + can mean pair-wise addition for arrays or matrix The return value must be a new object. A local variable is needed to create the new object before it can be returned. return statement will invoke copy constructor. Can be very inefficient if a large object creation and copy is made. Inherent problem in C++. We need to depend on compiler to optimize this. 813

15 Operator >> We can define this operator so that we can read an object using iostream. e.g. Complex a; cin >> a; Notice that the lhs operand is not of type Complex Member function is NOT possible. Always pass iostream objects by reference. Not even const (unless you don t do io in the fn). Invariably, these functions will need access to private variables and hence the friend access may be needed for this function. The return value should be reference to the stream object passed. 814

16 mutable Suppose we want to implement a class in which we have some private variables that are used for efficiency but not quite associate with the class itself. e.g. iterators for list use a private pointer curr. string class can have two variables datalength and lengthvalid flag to compute the length of string and store so that subsequent calls can use this for efficiency instead of recomputing. Length function uses these variables. Should Length be const fn? These functions should be allowed on const objects, but the compiler will not treat them as const functions. Soln: Define these variables as mutable. 815

17 Stream Input Consider reading an integer from cin. int sum, m, n; cin >> m >> n; sum = 0; while (cin >> m) { sum += m; } The value of cin >> m should be cin itself so that we can read n in cin >> m >> n; What should the value of cin >> m in while loop? If the value is cin, which is not NULL, it is always true and hence the loop should be infinite!!! 816

18 Stream Input (Contd) while loop expects an integer. The steam class provides an operator to cast cin to an int. That function ignores the pointer and returns the status of the stream (good or bad). The status of the stream should be bad after reading past end of file or after reading a bad input If the status of a steam is bad, no further input is possible until you clear the stream. When you open a file, if the file does not exist or it could not be opened, the stream is placed in a bad state. Thus, you cannot perform io. If you do, you will get garbage. 817

19 Stream Input (contd) iostream has 4 bits. enum io_state { goodbit = 0x00, eofbit = 0x01, failbit = 0x02, badbit = 0x04 }; Member Functions: int good() -- All ok int eof() -- stream encountered eof int fail() -- operation not successful int bad() -- operation invalid int rdstate() -- read current state void clear() -- restore to good state int operator!(); true if fail or bad bit is set. e.g. if (!cin) or if (! (cin >> n)) 818

20 Operator>> The operator>> is intended to read an object. If it sees end of file or it sees bad input, it should place the stream in a bad state. It is possible that the stream is placed in a bad state when doing io to read a subpart of the object. In that case, there is nothing to do. If the input read does not meet the expectation, we want to place the stream in bad state by doing fis.setstate(ios_base::failbit); To clear a stream, you can do fis.clear(); 819

21 Operator++ (or --) ++ and -- are unary operators. The impicit object is the operand. Since there are two types: pre and post, we need a way to distinguish between them. The pre-increment operator for a class Foo is written as Foo& operator++(); The post-increment operator for a class Foo is written as Foo& operator++(int); int argument is not used in the code and hence there is no need to specify the variable name. 820

22 Casting Operators You can write casting operators for a class Foo so that an object of type Foo can be converted to an object of another type. These are special member functions that have the syntax: operator <type>(); Note that there is no return type. Note that there is no parameter. class Foo { : operator int(); : } Foo a; int b; b = (int)a; <type> can be any type. e.g. int *, void *, char *, double, etc. 821

23 operator [] This operator overloading is meaningful for an object that has container objects. [] can be used to retrieve individual objects. For example, if we have a vector object, we can access or change individual members. The syntax is: <elemtype>& operator[](int index) const The return value is a reference object which can be used on lhs or rhs of an assignment statement. The return type can include the keyword const to prevent changes done on the object. Then, we can only retrieve the object but not change it. 822

24 Temporary Object It is possible to create temporary objects that can be useful in expressions. These temporary objects are automatically created and deleted by the compiler. We can create a temporary object by simply using the name of the class. Let us say we have a class called Rational that has a constructor function that takes an integer. Then, we can use it as follows: Rational a(1,2), b(1,4), c; c = a + b + Rational(2); The value of c will be 1/2+1/4+2 = 2 3/4 c = (int) a; // Need operator int(). 823

25 Inheritance If you define a class based on a previously defined class, the derived (or descendant) class is said to inherit many properties of the base (or ancestor) class. It is possible to have an hierarchy of classes arranged in a tree like structure. Inheritance describes the ability of a class to inherit information from ancestor classes. A class can be based on more than one base class in which case we are said to have multiple inheritance. We will avoid it in this course. It is complex and can lead to confusion if not used properly. 824

26 Why Inheritance? Inheritance enables the reuse of existing classes. Inheritance reduces the effort needed to add new features to an existing object. For example, we can have a class called Person and then create a new class called Student and yet another class called Faculty both of which are derived from Person. Features that are common to both classes are placed in Person and hence reduces the need for duplication of information in classes. When an object is created for a class, it is also considered to be an object of all super classes. 825

27 What is inherited? All member of the base class are inherited except the constructors and destructors. The derived class can add new members (both variables and functions) You cannot revise the ancestor s members. You can redefine member functions to have a different meaning in a derived class. You cannot redefine data members. When an object is created, remember that we need to initialize all variables and this will involve the constructor functions for ancestor classes. 826

28 Inheritance vs Access? The derived class inherits the private variables of the base class but cannot access them directly. Thus, we need to depend on constructor and member functions to deal with these variables. Inheritance does not mean accessibility. The member functions of a derived class can call public member functions of the base class. The member functions of a derived class cannot call private member functions of the base class. What if a function name, say Foo, is common to both classes? An object of a derived class will use the one in derived class and an object of the base class will use the one in base class. 827

29 Protected Members A class can have protected members in addition to public and private. protected members are not accessible to clients of the class. protected members are accessible to derived class. protected category helps to share information among the classes in a single path of the hierarchy without sharing that information with other clients In general, one should place variables in private section. Place them in protected if it is essential to share them with derived classes. 828

30 Kinds of Inheritance Public Inheritance: Both public and protected members of the base class remain public and protected members of the derived class. (i.e Keep same type of access) Protected Inheritance: Both public and protected members of the base class become protected members of the derived class. Private Inheritance: Both public and protected members of the base class become private members of the derived class. Note that the derived class keeps the same access or more stringent access (not more liberal access) 829

31 Data Initialization Since the derived class inherits all data members of the base class, we need to initialize them all. When an object of the derived class is created, we call the constructor function of the derived class. The constructor function of the derived class will automatically call the constructor function of the base class. Thus constructor functions are executed starting from the farthest ancestor to the derived class. Thus, a constructor function of a class is only responsible for initializing variables explicitly defined in that class not for those inherited. 830

32 Is-A Relationship If you find that two classes share is-a relationship, then it indicates that you can use public inheritance. An object of the derived class can be substituted for an object of the base class. (Object Type Compatibility). Thus, if a function expects a formal parameter to be of base type class, you can call it with derived class object. Object compatibility applies both to reference and value parameters. This leads to the issue of static vs dynamic (late) binding. 831

33 Has-A relationship A ball-point pen has ball has its point. You wouldn t want to use a ball wherever a pen is expected! You may not even want to use inheritance here. Make the ball as an object in the pen class. i.e it is a member of the pen class. has-a ==> containment When an object of type pen is created, an object of type ball is indirectly created and hence the constructor function for this should be called. This is done in the initializer list. Destructors are executed in reverse order. 832

34 As-A relationship You can implement stack as a list. When there is as-a relationship, consider private inheritance. Both has-a and as-a relationships are possible when public inheritance in inappropriate. When you have private inheritance, the public and protected members of the base class become private and hence are not accessible to any new derived classes. has-a is the simplest to use and is preferable if it is sufficient for your needs. 833

35 Private Inheritance If class D privately inherits from class B, then we can say that D is implemented in terms of B. Object of type D cannot be substituted for objects of type B. Private Inheritance means nothing during Software Design, only during Software implementation. Private inheritance means that implementation only is inherited; interface should be ignored. Example: Suppose we implement stack in terms of list. Clearly an object of type Stack has a different interface from an object of type List. List is used only to implement Stack. 834

36 Inheritance Syntax class Ball: public Sphere { : } class Ball: protected Sphere { : } class Ball: private Sphere { : } 835

37 Constructor Usage Ball::Ball():Sphere(),... { : } call the base class constructor Ball::Ball(int n):sphere(n),... { : } 836

38 early binding Let us assume that both Sphere and Ball classes have a function called Display. Consider the following examples: Sphere s1(3); Ball b1(4); Sphere *p = &s1; Sphere *q = &b1; s1.display(); // early binding b1.display(); // early binding p->display(); // late binding? q->display(); // late binding? Since p and q are pointers to Sphere, the last two calls will call Display in Sphere. Even the last one!! 837

39 Virtual Functions and Late Binding In the previous example, if we defined Display in Sphere class as a virtual function, then the last example will call the Display in Ball class rather than the one in Sphere class. Virtual keyword ==> Use the function in derived class if it has one. Assume that Display in sphere is declared as virtual. Sphere *p = &s1; p->display() will still call Display in Sphere as the object is an instance of Sphere, not Ball. So, the question of considering Display in Ball does not even arise. 838

40 What is Late Binding? Thus, the determination of which function to call for a particular statement in the code is done at run time rather than during compiler time. This is known as late or dynamic binding. Dynamic binding is possible for functions declared as virtual. Thus a virtual function can be overridden in the derived class. The function Display is called polymorphic. A polymorphic function has multiple meanings. If you want the function in derived class to override the one in base class, don t forger virtual! 839

41 Omission of Virtual keyword What happens if we omit virtual keyword? class Sphere { public: double Area() const; virtual Display() const; : } class Ball:public Sphere { public: double Area() const; } Ball class has Display function. 840

42 Ball b(10); Omitting Virtual Keyword b.display(); Let us say Display calls Area(). Since Area is not defined as virtual, the call to Area in Display will be interpreted by the compiler as the Area in Sphere (static binding). Thus the area function called will be the one in Sphere not the one in Ball. If we had defined Area as virtual, then the Area() function call in Display will use late binding and will call correctly the Area in Ball class. 841

43 Virtual Method Table The compiler creates a table for each class in which it keeps track of the pointer to the actual function to be called for each virtual function defined in the class. VMT is invisible to the programmer as it is automatically created and managed by the compiler. A call to the constructor establishes this table. Thus, VMT enables late (or dynamic) binding. 842

44 Abstract Class When a class defines a virtual function, normally the code for the function is also given. Virtual function means, use the one in base class unless it is overridden in the derived class. Thus the code for the base class virtual function is the most common use of the function. The code in derived classes are used to capture special cases. A base class can decide not to write the code for a virtual function. Thus, every derived class MUST provide one. Such a virtual function is called a pure virtual function. A class with at least one pure virtual function is called an abstract class. No instantiation allowed. 843

45 Abstract Class (contd) Abstract classes are useful to build an hierarchy of classes. We do not create an instance (i.e an object) of an abstract class. It is not allowed in C++. You declare a virtual function as pure by using = 0 virtual int Display() = 0; If a class does not have any virtual function, it means that it is meant to be used as a base class. If a class has at least one virtual function, you should normally declare the destructor as a virtual function too. It is highly recommended. If a class has no virtual function, don t declare destructor function as virtual. Bad idea. 844

46 Destructors and Inheritance When you have inheritance, the destructor functions are called in reverse order. What happens if we try to delete a derived class object using a base class pointer? The compiler will call the destructors starting only from the base class going up in the hierarchy. But,we want to call destructors starting from the most specific class. The solution is to make the destructor function virtual in base classes. One twist: If you want to make a class abstract but you have no pure virtual functions, what do you do? Make the destructor a pure virtual function. But, you must provide code for this destructor fn. 845

Short Notes of CS201

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

CS201 - Introduction to Programming Glossary By

CS201 - 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 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 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

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

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

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

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

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

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

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

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

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

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Interview Questions of C++

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

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

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

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

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer June 3, 2013 OOPP / C++ Lecture 9... 1/40 Const Qualifiers Operator Extensions Polymorphism Abstract Classes Linear Data Structure Demo Ordered

More information

C++ (Non for C Programmer) (BT307) 40 Hours

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

Object-Oriented Design (OOD) and C++

Object-Oriented Design (OOD) and C++ Chapter 2 Object-Oriented Design (OOD) and C++ At a Glance Instructor s Manual Table of Contents Chapter Overview Chapter Objectives Instructor Notes Quick Quizzes Discussion Questions Projects to Assign

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

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

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

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

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 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?

More information

More Advanced Class Concepts

More Advanced Class Concepts More Advanced Class Concepts Operator overloading Inheritance Templates PH (RH) (Roger.Henriksson@cs.lth.se) C++ Programming 2016/17 146 / 281 Operator Overloading In most programming languages some operators

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

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

eingebetteter Systeme

eingebetteter Systeme Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Tutorial (falk@cs.fau.de) 1 Agenda Classes Pointers and References Functions and Methods Function and Operator Overloading Template Classes

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

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

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

class Polynomial { public: Polynomial(const string& N = no name, const vector<int>& C = vector<int>());... }; Default Arguments 1 When declaring a C++ function, you may optionally specify a default value for function parameters by listing initializations for them in the declaration: class Polynomial { public:

More information

Data Structures and Other Objects Using C++

Data Structures and Other Objects Using C++ Inheritance Chapter 14 discuss Derived classes, Inheritance, and Polymorphism Inheritance Basics Inheritance Details Data Structures and Other Objects Using C++ Polymorphism Virtual Functions Inheritance

More information

Advanced C++ Topics. Alexander Warg, 2017

Advanced C++ Topics. Alexander Warg, 2017 www.kernkonzept.com Advanced C++ Topics Alexander Warg, 2017 M I C R O K E R N E L M A D E I N G E R M A N Y Overview WHAT IS BEHIND C++ Language Magics Object Life Time Object Memory Layout INTRODUCTION

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

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

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

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

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

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

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Overloaded Operators, Functions, and Students

Overloaded Operators, Functions, and Students , Functions, and Students Division of Mathematics and Computer Science Maryville College Outline Overloading Symbols 1 Overloading Symbols 2 3 Symbol Overloading Overloading Symbols A symbol is overloaded

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

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

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

COEN244: Class & function templates

COEN244: Class & function templates COEN244: Class & function templates Aishy Amer Electrical & Computer Engineering Templates Function Templates Class Templates Outline Templates and inheritance Introduction to C++ Standard Template Library

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 12 Thomas Wies New York University Review Last lecture Modules Outline Classes Encapsulation and Inheritance Initialization and Finalization Dynamic

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

Decaf Language Reference Manual

Decaf Language Reference Manual Decaf Language Reference Manual C. R. Ramakrishnan Department of Computer Science SUNY at Stony Brook Stony Brook, NY 11794-4400 cram@cs.stonybrook.edu February 12, 2012 Decaf is a small object oriented

More information

Time : 3 hours. Full Marks : 75. Own words as far as practicable. The questions are of equal value. Answer any five questions.

Time : 3 hours. Full Marks : 75. Own words as far as practicable. The questions are of equal value. Answer any five questions. XEV (H-3) BCA (6) 2 0 1 0 Time : 3 hours Full Marks : 75 Candidates are required to give their answers in their Own words as far as practicable. The questions are of equal value. Answer any five questions.

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

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

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

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

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

AIMS Embedded Systems Programming MT 2017

AIMS Embedded Systems Programming MT 2017 AIMS Embedded Systems Programming MT 2017 Object-Oriented Programming with C++ Daniel Kroening University of Oxford, Computer Science Department Version 1.0, 2014 Outline Classes and Objects Constructors

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

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli

Learning Objectives. C++ For Artists 2003 Rick Miller All Rights Reserved xli Identify and overcome the difficulties encountered by students when learning how to program List and explain the software development roles played by students List and explain the phases of the tight spiral

More information

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions. Dr.G.R.Damodaran College of Science (Autonomous, affiliated to the Bharathiar University, recognized by the UGC)Reaccredited at the 'A' Grade Level by the NAAC and ISO 9001:2008 Certified CRISL rated 'A'

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured

The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Introduction p. xxix The Foundation of C++: The C Subset An Overview of C p. 3 The Origins and History of C p. 4 C Is a Middle-Level Language p. 5 C Is a Structured Language p. 6 C Is a Programmer's Language

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Evaluation Issues in Generic Programming with Inheritance and Templates in C++

Evaluation Issues in Generic Programming with Inheritance and Templates in C++ Evaluation Issues in Generic Programming with Inheritance and Templates in C++ Emil Vassev, Joey Paquet Department of Computer Science and Software Engineering Concordia University Montreal, Quebec, H3G

More information

END TERM EXAMINATION

END TERM EXAMINATION END TERM EXAMINATION THIRD SEMESTER [BCA] DECEMBER 2007 Paper Code: BCA 209 Subject: Object Oriented Programming Time: 3 hours Maximum Marks: 75 Note: Attempt all questions. Internal choice is indicated.

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

Computer Science 306 Study Guide

Computer Science 306 Study Guide Computer Science 306 Study Guide C++ for Programmers Computer Science 306 Study Guide (Print Version) Copyright and Credits - Unit 0 - Introduction to C++ for Programmers Section 1 - The programming environment

More information

SFU CMPT Topic: Class Templates

SFU CMPT Topic: Class Templates SFU CMPT-212 2008-1 1 Topic: Class Templates SFU CMPT-212 2008-1 Topic: Class Templates Ján Maňuch E-mail: jmanuch@sfu.ca Monday 3 rd March, 2008 SFU CMPT-212 2008-1 2 Topic: Class Templates Class templates

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

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

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

CS201 Some Important Definitions

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

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object CHAPTER 1 Introduction to Computers and Programming 1 1.1 Why Program? 1 1.2 Computer Systems: Hardware and Software 2 1.3 Programs and Programming Languages 8 1.4 What is a Program Made of? 14 1.5 Input,

More information

Module Operator Overloading and Type Conversion. Table of Contents

Module Operator Overloading and Type Conversion. Table of Contents 1 Module - 33 Operator Overloading and Type Conversion Table of Contents 1. Introduction 2. Operator Overloading 3. this pointer 4. Overloading Unary Operators 5. Overloading Binary Operators 6. Overloading

More information

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures

Outline. A C++ Linked Structure Class A C++ Linked List C++ Linked Dynamic Memory Errors In-class work. 1 Chapter 11: C++ Linked Structures Outline 1 Chapter 11: C++ Linked Structures A ListNode Class To support a Linked List container class LList, a ListNode class is used for the individual nodes. A ListNode object has two attributes: item

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

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How

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

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages CSE 307: Principles of Programming Languages Classes and Inheritance R. Sekar 1 / 52 Topics 1. OOP Introduction 2. Type & Subtype 3. Inheritance 4. Overloading and Overriding 2 / 52 Section 1 OOP Introduction

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

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

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

04-24/26 Discussion Notes

04-24/26 Discussion Notes 04-24/26 Discussion Notes PIC 10B Spring 2018 1 When const references should be used and should not be used 1.1 Parameters to constructors We ve already seen code like the following 1 int add10 ( int x

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

KLiC C++ Programming. (KLiC Certificate in C++ Programming)

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

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

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information