Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune

Size: px
Start display at page:

Download "Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune"

Transcription

1 C++ and Java

2 Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune Prof. M. K. Ghadoliya Director, School of Distance Education and Learning Jaipur National University, Jaipur Subject Expert Panel Dr. Ramchandra G. Pawar Director, SIBACA, Lonavala Pune Ashwini Pandit Subject Matter Expert Content Review Panel Gaurav Modi Subject Matter Expert Shubhada Pawar Subject Matter Expert Copyright This book contains the course content for C++ and Java. First Edition 2013 Printed by Universal Training Solutions Private Limited Address 05 th Floor, I-Space, Bavdhan, Pune All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted.

3 Index I. Content...II II. List of Figures... V III. List of Tables...VI IV. Abbreviations... VII V. Application VI. Bibliography VII. Self Assessment Answers Book at a Glance I

4 Contents Chapter I... 1 Object Oriented Programming... 1 Aim... 1 Objectives... 1 Learning outcome Introduction to OOP Basic Concepts of Object-Oriented Programming Paradigms of Programming Languages Imperative Paradigm Declarative Paradigm Characteristics of Object-Oriented Programming Advantages of Object Oriented Programming... 8 Summary References Recommended Reading Self Assessment...11 Chapter II Classes and Objects Aim Objectives Learning outcome Introduction to Classes Specifying a Class Creating Objects Defining Member Functions Static Data Members Static Member Functions Pointer to Members Constructor Copy Constructor Destructors Summary References Recommended Reading Self Assessment Chapter III Inheritance and Polymorphism Aim Objectives Learning outcome Introduction to Inheritance Single Inheritance Multiple Inheritance Polymorphism Summary References Recommended Reading Self Assessment II

5 Chapter IV Templates and Exception Handling Aim Objectives Learning outcome Introduction to Templates Function Templates A Simple Function Template Class Templates Exceptions Exception Syntax Throwing an Exception Handling Exceptions Summary References Recommended Reading Self Assessment Chapter V Introduction to JAVA Aim Objectives Learning outcome Concept of Java Origin of Java A Virtual Machine Java in Comparison to Other Languages Object Oriented Programming Concepts in Java Types concept in JAVA Summary References Recommended Reading Self Assessment Chapter VI Classes, Objects and Methods Aim Objectives Learning outcome Introduction Defining a Class Fields Declaration Methods Declaration Creating Objects Summary References Recommended Reading Self Assessment III

6 Chapter VII Inheritance and Polymorphism in JAVA Aim Objectives Learning outcome Inheritance in JAVA Protected Access Overriding Methods Dynamic Method Dispatching The Super Keyword Final Methods and Final Classes Interfaces The Implements Declaration Polymorphism Method Calling Binding Producing the Right Behaviour Extensibility Overriding vs Overloading Abstract Classes and Methods Constructors and Polymorphism Order of Constructor Calls Summary References Recommended Reading Self Assessment Chapter VIII Exception Handling in Java Aim Objectives Learning outcome Introduction to Exception Handling The Classification of Exceptions Advertising the Exceptions that a Method Throws How to Throw an Exception Creating Exception Classes Catching Exceptions Catching Multiple Exceptions Rethrowing Exceptions Summary References Recommended Reading Self Assessment IV

7 List of Figures Fig. 1.1 Property inheritance... 4 Fig. 1.2 Polymorphism... 4 Fig. 1.3 Message passing... 5 Fig. 1.4 Language paradigm... 6 Fig. 1.5 An object... 7 Fig. 2.1 Representation of a class Fig. 3.1 Adding more members to a class (by public derivation) Fig. 3.2 Adding more members to a class (by private derivation) Fig. 3.3 Multiple Inheritance Fig. 3.4 Polymorphism Fig. 5.1 The Java runtime environment Fig. 5.2 Programming languages compared Fig. 5.3 Inheritance Fig. 6.1 Creating object references Fig. 6.2 Assigning one object reference variable to another Fig. 7.1 Accessibility in an inheritance relationship Fig. 7.2 Inheritance diagram Fig. 7.3 Addition of methods and classes to the instrument Fig. 7.4 Instrument class into abstract class Fig. 8.1 Exception hierarchy in Java V

8 List of Tables Table 1.1 Procedural and object oriented paradigms... 6 Table 1.2 Functional and logical paradigms... 7 Table 7.1 Access to class A s members VI

9 Abbreviations ADT - Abstract Data Types GUI - Graphical User Interface HTML - Hyper Text Markup Language ITV - Interactive TV OOP - Object Oriented Programming PDAs - Personal Digital Assistants SEI - Software Engineering Institute VII

10

11 Chapter I Object Oriented Programming Aim The aim of this chapter is to: explain the basic concepts of object-oriented programming discuss different language paradigms describe data abstraction and encapsulation Objectives The objectives of this chapter are to: elucidate inheritance determine the characteristics of object-oriented programming explain object orientation Learning outcome At the end of this chapter, you will be able to: analyse dynamic binding enlist the advantages of object-oriented programming comprehend the characteristics of OOP 1

12 C++ and Java 1.1 Introduction to OOP Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application composed of multiple objects which are connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. With OOP, every object can handle data, get messages, and transfer messages to other objects. The objects will all act as independent units in their own right, and they will be responsible for carrying out a certain process. Because the objects are not dependent on each other, OOP is seen as being more flexible than older methods of programming. It has become quite popular, and it is now used in a number of advanced software engineering projects. Many programmers feel that object oriented programming is easier for beginners to learn than previous programming methods. Because it is easier to learn, it can also be analysed and maintained without a large amount of difficulty. However, there are some people who feel that OOP is more complicated than older programming methods. 1.2 Basic Concepts of Object-Oriented Programming The basic concepts used extensively in object-oriented programming are as follows: Objects Classes Data abstraction and encapsulation Inheritance Polymorphism Dynamic binding Message passing Objects An object can be considered a thing that can perform a set of related activities. The set of activities that the object performs defines the object s behaviour. For example, the hand can grip something or a Student (object) can give the name or address. In pure OOP terms, an object is an instance of a class. Object is defined as an identifiable entity with some characteristic and behaviour. For instance, we can say Orange is an object. Its characteristics are: it is spherical shaped; its colour is orange, etc. Its behaviour is: it is juicy and it tastes sweet-sour. While programming using OOP approach, the characteristics of an object are represented by its data and its behaviour is represented by its functions associated. Therefore, in OOP, programming object represents an entity that can store data and has its interface through functions. Programming problem is analysed in terms of objects and the nature of communication between them, so it is necessary for us to understand the nature of communication between objects. Classes The objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In other words, objects are variables of the type class. Once a class has been defined, any number of objects belonging to that class can be created. Each object is associated with the data of type class with which they are created. Thus, a class is a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. The syntax used to create an object is no different than the syntax used to create an integer object on C. 2

13 If fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit. Data abstraction and encapsulation The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only these functions which are wrapped in the class can access it. The encapsulation is the inclusion within a program object of all the resources needed for the object to function - basically, the methods and the data. In OOP, the encapsulation is mainly achieved by creating classes; the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do. Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions. Since the classes use the concept of data abstraction, they are known as abstract data types (ADT). Inheritance Inheritance is the process by which objects of one class obtain the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird robin is a part of the class flying bird which is again a part of the class bird. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as shown in the figure below. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features of an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what has been planned. Each sub-class defines only those features that are unique to it. Without the use of classification, each class would have to explicitly include all of its features. 3

14 C++ and Java Bird Attributes Feathers Lay eggs Flying Bird Attributes Nonflying Bird Attributes Robin Attributes Swollen Penguin Kiwi Attributes Attributes Attributes Polymorphism Fig. 1.1 Property inheritance Polymorphism is another important OOP concept. Polymorphism, a Greek term, refers to the ability to take more than one form. An operation may exhibit different behaviours in different instances. Behaviour depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. The figure given below illustrates that a single function name can be used to handle different number and different types or arguments. This is something similar to a particular world having different meanings depending on the context. Using a single function name to perform different types of tasks is known as function overloading. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance. Shape Draw( ) Circle-object Box-object Triangle object Draw (circle) Draw (box) Draw (triangle) Fig. 1.2 Polymorphism 4

15 Dynamic binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with a polymorphic reference depending on the dynamic type of that reference. Consider the procedure draw in the figure above. By inheritance, every object will have this procedure. Its algorithm is, however, unique to each object and so the draw procedure will be redefined in each class that defines the object. At run-time, the code matching the object under current reference will be called. Message passing An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, therefore, involves the following basic steps: Creating classes that define objects and their behaviour Creating objects from class definitions Establishing communication among objects Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. A message for an object is a request for execution of a procedure, and therefore, will invoke a function (procedure) in the receiving object, the name of the function (message) and the information to be sent. An example is shown as the figure given below: Employee Salary (Name) Object Information Message Fig. 1.3 Message passing Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive. 1.3 Paradigms of Programming Languages The term paradigm describes a set of techniques, methods, theories and standards that together represent a way of thinking for problem solving. According to Wegner, paradigms are patterns of thought for problem solving. Language paradigms were associated with classes of languages. First, the paradigms are defined. Thereafter, programming languages according to the different paradigms are classified. The language paradigms are divided into two parts: imperative and declarative paradigms, as shown in figure below. Imperative languages can be further classified into procedural and object-oriented approach. Declarative languages can be classified into functional languages and logical languages. In the figure below, the examples of languages in each category are also given. 5

16 C++ and Java Language Paradigm Imperative Paradigm Declarative Paradigm Procedural Object Oriented Functional Logical C, Pascal C++ Simula, Java Lisp Prolog Imperative Paradigm Fig. 1.4 Language paradigm The meaning of imperative is expressing a command or order. So, the programming languages in this category specify the step-by-step explanation of command. Imperative programming languages describe the details of how the results are to be obtained in terms of the underlying machine model. The programs specify step-by-step the entire set of transitions that the program goes through. The program starts from an initial state, goes through the transitions and reaches a final state. Within this paradigm, we have the procedural approach and object-oriented approach. Procedural paradigm Procedural languages are statement oriented with the variables holding values. The execution of a program is modelled as a series of states of variable locations. Non-executable statements allocate memory, bind symbolic names to absolute memory locations and initialise memory. The popular programming languages in this category are Ada, FORTRAN, Basic, Algol, Pascal, COBOL, Modula, C, etc. Object-oriented paradigm The object-oriented paradigm is centred on the concept of the object. Everything is focused on objects. Can we think what an object is? Program consists of two things: first, a set of objects and second, the way they interact with each other. Computation in this paradigm is viewed as the simulation of real world entities. The popular programming languages in this paradigm are C++, Smalltalk and Java. Table 1.1 Procedural and object oriented paradigms 6

17 1.3.2 Declarative Paradigm In this paradigm, programs declare or specify what is to be computed without specifying how it is to be achieved. Declarative programming is also known as value-oriented programming. Declarative languages describe the relationship between variables in terms of functions and inference rules. The language executor applies a fixed method to these relations to produce a desired result. It is mainly used in solving artificial intelligence and constraint-satisfaction problems. Declarative paradigm is further divided into two categories: functional and logical paradigms. Functional paradigm A programme consists of a collection of functions. A function just calculates and returns a value. A program consists of calling a function with appropriate arguments, but any function can make use of other functions also. Logical paradigm In this paradigm programs only explain what is to be computed not how to compute it. Here program is represented by a set of relationships, between objects or property of objects known as predicate which are held to be true, and a set of logic/clauses (i.e., if A is true, then B is true). The main programming languages in this category are Lisp, ML Scheme, and Haskell. Normally, logical paradigm, integrates data and control structures. The Prolog language is perhaps the most common example. Mercury language is a more modern attempt at creating a logic programming language. Table 1.2 Functional and logical paradigms 1.4 Characteristics of Object-Oriented Programming The fundamental concept of object-oriented programming is that it allows combination of data and functions, methods and procedures which are working on that data, which did not exist in earlier procedure-based programming paradigms. This fundamental unit is called object. An object has a well-defined interface, which is the only way to access the object s data. Thus, the data is wellorganised and hidden. Such hidden data is known as encapsulated. The basic terms used in OOPs include data encapsulation and data hiding. Data Procedures / Functions / Methods Fig. 1.5 An object 7

18 C++ and Java An object-oriented programming system is composed of multiple objects. When one object needs information from another object, a request is sent asking for specific information. For example, a report object may need to know what is today s date and will send a request to the date object. These requests are called messages and each object has an interface that manages messages. A primary rule of object-oriented programming paradigm is as the user of an object, we never need to peek inside it. All communications among the objects is done via messages. Messages define the interface to the object. The object to which a message is sent is called the receiver of the message. Everything an object can do is represented by its message interface. So, we need not know anything about what is in the object in order to use it. If we look inside the objects, it may tempt us and we would like to tamper with the details of how the object works. Suppose, we have changed the object and later the person who programmed and designed the object in the first place decided to change some of these details, then we may be in trouble. Our software may not be working correctly. But as long as we just deal with objects via their messages, the software is guaranteed to work. Thus, it is important that access to an object is provided only through its messages, while keeping the details hidden. But why should we be concerned about the changes in the object design? Because software engineering experiences tell that software do change. A popular saying is that software is not written, it is re-written. Some of the costliest mistakes in computer history are because of software that failed when someone tried to change it. The basic characteristics of object-oriented programming are as follows: The basic programming entity is the object. An object can be considered to be a variable that stores data and can perform operation on the stored data itself. An object oriented program is a collection of objects for solving a problem. These objects send messages to each other. A message can be equated to a request to call a function of the receiver object. Each object has its own memory or data that may be made up of other objects. Thus, object-oriented programs are suitable for complex problem solving as they hide the complexity behind the simplicity of objects. Each object can be related to a type, which is its class. An important consideration of a class is that it specifies the message interface, i.e., the messages that can be sent to that type/class of the objects. All object of a particular class can receive the same messages, but may behave differently. This leads to an important conclusion. For example, a circle object having centre at x=0 and y=0 and a radius of 1 cm is of the class circle. However, it is also of the type shape. Thus, this object is bound to accept the messages that can be sent to class shape. Similarly, a rectangle object is of type rectangle and also of type shape and will follow messages sent to class shape. Both these objects may be handled using the type shape, but may respond to a message differently on receiving the same message. This is one of the most powerful concepts of object-oriented programming language, which involves inheritance and polymorphism. 1.5 Advantages of Object Oriented Programming The popularity of object-oriented programming (OOP) was because of its methodology, which allowed breaking complex and large software programs into simpler, smaller and manageable components. The costs of building large monolithic software were enormous. Moreover, the fundamental things in object-oriented programming are objects which model real world objects. Following are the basic advantages of object-oriented systems: Modular design: The softwares built around OOP are modular, because they are built on objects. The objects are entity in themselves, whose internal working is hidden from other objects and is decoupled from the rest of the program. Simple approach: The objects, model real world entities, which results in simple program structure. Modifiable: Because of its inherent properties of data abstraction and encapsulation, the internal working of objects is hidden from other objects. Thus, any modification made to them should not affect the rest of the system. 8

19 Extensible: The extension to the existing program for its adaptation to new environment can be done by simply adding few new objects or by adding new features in old classes/types. Flexible: Software built on object-oriented programming can be flexible in adapting to different situations because interaction between objects does not affect the internal working of objects. Reusable: Objects once made, can be reused in more than one program. Maintainable: Objects are separate entities, which can be maintained separately allowing fixing of bugs or any other change easily. 9

20 C++ and Java Summary Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application composed of multiple objects which are connected to each other. An object can be considered a thing that can perform a set of related activities. The set of activities that the object performs defines the object s behaviour. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In other words, objects are variables of the type class. The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. Abstraction refers to the act of representing essential features without including the background details or explanations. Inheritance is the process by which objects of one class obtain the properties of objects of another class. It supports the concept of hierarchical classification. Polymorphism is an important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. The term paradigm describes a set of techniques, methods, theories and standards that together represent a way of thinking for problem solving. References Nirosh, 2011, Introduction to Object-Oriented Programming Concepts and More [Online] Available at < [Accessed 3 November 2011]. Stroustrup, B., A Tour of C++ [Online] Available at < aspx?p=25003&seqnum=3> [Accessed 3 November 2011]. Balagurusamy, E., Object Oriented Programming with C++, 3rd ed., Tata McGraw-Hill Publishing. Parsons, D., Object Oriented Programming with C++, 2nd ed., Cengage Learning EMEA. VTC, C++ Fundamentals: 06. Classes Objects [Video Online] Available at: < watch?v=uh3trix8bdo> [Accessed 3 November 2011]. FreeComputerTutor, Object oriented programming [Video Online] Available at: < com/watch?v=hx1q9wq5qmk> [Accessed 3 November 2011]. Recommended Reading Lafore, R., Object Oriented Programming in C++, 4th ed., Pearson Education India, Dorling Kindersley (India) Pvt. Ltd. Farrell, J., Object Oriented Programming using C++, 4th ed., Course Technology, USA, Cengage Learning. Johnsonbaugh, R. & Kalin, M., Object-Oriented Programming in C++, 2nd ed., Prentice Hall. 10

21 Self Assessment 1. is defined as an identifiable entity with some characteristic and behaviour. a. Object b. Class c. Data d. Name What refers to user-defined data types and behave like the built-in types of a programming language? a. Data b. Keywords c. Classes d. Object is the most striking feature of a class. a. Data encapsulation b. Inheritance c. Polymorphism d. Message passing Which of the following statements is false? a. Inheritance supports the concept of hierarchical classification. b. In C++, the concept of inheritance provides the idea of reusability. c. Inheritance is the process by which objects of one class obtain the properties of objects of another class. d. Each sub-class defines only those features that are unique to it Which of the following statements is true? a. Polymorphism, an Arabic term, means the ability to take more than one form. b. Inheritance, a Latin term, means the ability to take more than one form. c. Polymorphism, a Greek term, means the ability to take more than one form. d. Polymorphism, a German term, means the ability to take more than one form. Polymorphism is extensively used in inheritance. a. implementing b. calculating c. forcing d. carrying The wrapping up of data and functions into a single unit (called class) is known as a. polymorphism b. object c. encapsulation d. inheritance 11

22 C++ and Java Which of the following is not an advantage of OOP? a. Modular design b. Flexibility c. Extensible d. Linearity An object-oriented programming system is composed of a. multiple objects b. single object c. multiple classes d. multiple events 10. Polymorphism is extensively used in implementing a. encapsulation b. inheritance c. objects d. classes 12

23 Chapter II Classes and Objects Aim The aim of this chapter is to: introduce the concept of classes explain the method of specifying a class differentiate between class and structure Objectives The objectives of this chapter are to: discuss static data members define constructor explain the process of accessing class members Learning outcome At the end of this chapter, you will be able to: comprehend concept of destructors describe the pointer to members and static member functions define member functions 13

24 C++ and Java 2.1 Introduction to Classes The basic building blocks of object oriented programming are classes and objects. Classes The characteristic features of a class are given below. A class is a user defined data type with data elements and operations. Classes are the data members that describe the state of the object. Classes are the operations that define the behavior of the object. Typically, a class is used to introduce a new user defined data type and define abstractions that do not map naturally into predefined or derived data types. Class name Attributes Operations Attributes denote static and dynamic properties. Fig. 2.1 Representation of a class An operation denotes an attributes service that a class offers to its clients (objects). For example, a zoo animal class, an employee class etc. C structures is one of the unique features of the C language is structures. It provides a method for packing together data of different type. A structure is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. Once the structure is defined, we can create variables of that type using declarations that are similar to the built-in type declaration. For example: Struct student char name[20]; int roll_number; float total_marks; ; The keyword struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. The identifier student referred to as structure name or structure tag, can be used to create variables of type student. 14

25 Differences between class and structure In C++, structures can have member functions but the default scope of the members of the structure is public. The default scope of the class is private. Structures don t have access restrictions as public, private and protected as in the class. Like class, structures can not be inherited. Structures can not have constructors and destructors. 2.2 Specifying a Class A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary, from external use. While defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. A class specification has two parts: Class declaration Class function definitions class class_name private: variable declarations; functions declarations; public: variable declarations; functions declarations; ; The keyword class specifies what follows is an abstract data of type class_name. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class. For example: class item int number; // variables declaration float cost; // private by default public: void getdata (int a, float b); // functions declaration void putdata (void); // using prototype : // ends with semicolon We usually give a class some meaningful name, such as item, this name now becomes a new type identifier that can be used to declare instances of that class type. The class item contains two data members and two functions. The class item contains two data members and two functions members. The data members are private by default while both the functions are public by declaration. The function getdata() can be used to assign values to the member variables number and cost, and putdata() can be used for displaying their values. 15

26 C++ and Java 2.3 Creating Objects Once a class has been declared, we can create variables of that type by using the class name, for example: item x; // memory for x is created creates a variable x of type item. In C++, the class variables are known as objects. Therefore, x is called an object of type item. We may also declare more than one object in one statement. For example: item x,y,z; Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. Class item x,y,z; Accessing class members The private data of a class can be accessed only through the member functions of that class. The main() cannot contain statements that access number and cost directly. The following is the format for calling a member function: Object-name. function-name (actual-agruments); For example, the function call statement x.getdata(100, 75.5) is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing getdata() function. The assignments occur in the actual function. 2.4 Defining Member Functions Member functions can be defined in two places: Outside the class definition Inside the class definition Outside the class definition Member functions that are declared inside a class have to be defined separately outside the class. Their definitions are very much like the normal functions. They should have a function header and a function body. An important difference between a member function and a normal function is that a member function incorporates a membership identify label in the header. This label tells the compiler which class the function belongs to. The general form of a member function definition is: return-type class-name :: function-name (argument declaration) function body 16

27 The membership label class-name:: tells the compiler that the function function-name belongs to the class classname. That is, the scope of the function is restricted to the class-name specified in the header line. The symbol :: is called the scope resolution operator. Since these functions do not return any value, their return-type is void. The member functions have some special characteristics that are often used in the program development. These characteristics are: Several different classes can use the same function name; the membership label will resolve their scope. Member functions can access the private data of the class. A non-member function cannot do so. A member function can call another member function directly, without using dot operator. Inside the class definition Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. For example, we could define the item class as follows: class item int number; float cost; public: void getdata( int a, float b); // declarations // inline function void purdata (void) cout << number << \n ; cout << cost << \n ; ; When a function is defined inside a class, it is treated as an inline function. Therefore, all the restrictions and limitations that apply to an inline function are also applicable here. Normally, only small functions are defined inside the class definition. 2.5 Static Data Members A static member of a class can be qualified as static. The properties of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics. These are: It is initialised to zero when the first object of its class is created. No other initialisation is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurrences of all the objects. The program below illustrates the use of a static data member. #include >instream> using namespace std; class item static int count; int number; public; 17

28 C++ and Java void getdata (int a) number = a; count ++; void getcount (void) cout << count: ; cout << count << \n ; ; int item :: count; int main () item a, b, c; a.getcount (); b.getcount (); c.getdata (); // count is intialised to zero // display count a.getdata (100); // getting data into object a b.getdata (200); // getting data into object b c.getdata (300); // getting data into object c cout << After reading data << \n ; a.getcount (); // display count b.getcount (); c.getdata (); return o; The output of the program would be: count: 0 count: 0 count: 0 After reading data count: 3 count: 3 count: 3 Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than a part of an object, they are also known as class variables. 2.6 Static Member Functions Like static member variable, we can also have static member functions. A member function that is declared static has the following properties: A static function can have access to only other static members (functions or variables) declared in the same class. A static member function can be called using the class name (instead of its objects as follows: Class-name:: function-name; Const member functions If a member function does not alter any data in the class, then we may declare it as a const member function as follows: 18

29 void mul (int, int) const; double get_balance () const; The qualifier const is appended to the function prototypes (in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values. 2.7 Pointer to Members It is possible to take the address of a member of a class and assign it to a pointer. The address of a member can be obtained by applying the operator and to a fully operator class member name. A class member pointer can be declared using the operator:: * with the class name. For example, given the class: class a private: int m; public: void show (); ; We can define a pointer to the member m as follows: int A::* ip = &A ::m; The ip pointer created thus, acts like a class member in that it must be invoked with a class object. In the statement above, the phrase A::* means pointer-to-member of A class. The phrase & A::m means the address of the member of A class. Remember, the following statement is not valid: int*ip = &m; // won t work This is because m is not simply an int type data. The dereferencing operator->* is used to access a member when we use pointers to both the object and the member. The dereferencing operator * is used when the object itself is used with the member pointer. Note that *ip is used like a member name. 2.8 Constructor A constructor is a special member function whose task is to initialise the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows: // class with a constructor class integer int m, n; public: interger (void); // constructor declared.... ; interger :: integer (void) // constructor declared m=0; n=0; 19

30 C++ and Java When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialised automatically. For example, the declaration: integer int1; // object int1 created not only creates the object int1 of type integer but also initialises its data members m and n to zero. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A (). If no such constructor is defined, then the compiler supplies a default constructor. Therefore, a statement such as A a; invokes the default constructor of the compiler to create the object a. The constructor functions have some special characteristics. These are: They should be declared in the public section. They are invoked automatically when the objects are created. They do not have return types, not even void and therefore, and they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, they can have default arguments. Constructors cannot be virtual. We cannot refer to their addresses Copy Constructor Copy constructor initialises an object by copying the state from another object of the same class. Whenever an object is copied, another object (the copy) is created, this constructor is called copy constructor. If the class of the object being copied is A, the copy constructor s signature is usually A::A (const A&). Default copy constructor provided by the compiler does member wise copy. Usually overridden when an object has data members that are pointers. For example: # include <iostream> using namespace std; class code int id; public: code() 20 //constructor code(int a) id = a; // constructor again code(code & x) id = x.id; // copy in the value void display(void) cout << id; ; int main code A(100); code B(A); // object A is created and initialised // copy constructor called

31 code C=A; // copy constructor called again code D; // D is created, not initialised D = A; // copy constructor not called cout << \n id of A: ; A.display(); cout << \n id of B: ; B.display(); cout << \n id of C: ; C.display(); cout << \n id of D: ; D.display(); return 0; The ouput of the program is: id of A: 100 id of B: 100 id of C: 100 id of D: 100 When no copy constructor is defined, the compiler supplies its own copy constructor. 2.9 Destructors A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor for the class integer can be defined as shown below: -integer () A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler upon exit from the program (or block or function as the case may be) to clean up storage that is no longer accessible. It is good a practice to declare destructors in a program since it releases memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. For example, the matrix class may be defined as follows. matrix :: matrix() for(int i=0; i<d1; i++) delete p[1] delete p; The example below illustrates that the destructor has been invoked implicitly by the compiler. #include <iostream> using namespace std; int count = 0; class alpha public: alpha() count++; cout << \nno. Of object created << count; alpha() cout << \nno. Of object destroyed <<count; 21

32 C++ and Java ; int main() cout << \n\nenter MAIN\n ; alpha A1, A2, A3, A4; cout << \n\nenter BLOCK\n ; alphs A5; cout << \n\nenter BLOCK2\n ; alpha A6; cout << \n\nre-enter MAIN\n ; return 0; Output of the program: ENTER MAIN No. of object created 1 No. of object created 2 No. of object created 3 No. of object created 4 ENTER BLOCK1 No. of object created 5 No. of object destroyed 5 ENTER BLOCK 2 No. of object created 5 No. of object destroyed 5 RE-ENTER MAIN No. of object destroyed 4 No. of object destroyed 3 No. of object destroyed 2 No. of object destroyed 1 22

33 Summary The basic building blocks of object oriented programming are classes and objects. Attributes denote static and dynamic properties. An operation denotes an attributes service that a class offers to its clients (objects). A structure is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. The keyword class specifies what follows is an abstract data of type class_name. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. Once a class has been declared, we can create variables of that type by using the class name Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. The private data of a class can be accessed only through the member functions of that class. Member functions can be defined in two places: outside the class definition, and inside the class definition An important difference between a member function and a normal function is that a member function incorporates a membership identify label in the header Another method of defining a member function is to replace the function declaration by the actual function definition inside the class A static member variable has certain special characteristics. These are: it is initialised to zero when the first object of its class is created. No other initialisation is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created, and it is visible only within the class, but its lifetime is the entire program. The type and scope of each static member variable must be defined outside the class definition. If a member function does not alter any data in the class, then we may declare it as a const member function A constructor is a special member function whose task is to initialise the objects of its class. It is special because its name is the same as the class name. Copy constructor initialises an object by copying the state from another object of the same class. A destructor is used to destroy the objects that have been created by a constructor. References Balagurusamy, E., Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill. Jana, D., C++ and Object-Oriented Programming Paradigm, 2nd ed., PHI Learning Pvt. Ltd. C++ Tutorial 11: Classes and Objects in C++ [Video Online] Available at: < watch?v=5czamjymyja> [Accessed 14 November 2011]. C++ Programming [13] - Classes (part 1), 2010 [Video Online] Available at: < watch?v=3x0lpqrofxg> [Accessed 14 November 2011]. Exforsys Inc., C++ Objects and Classes [Online] Available at: < [Accessed 14 November 2011]. Intap.net, What is an object? [Online] Available at: < [Accessed 14 November 2011]. Recommended Reading Lafore, R., Object-Oriented Programming in C++, 4th ed., Sams. Koffman, E.B., Objects, Abstraction, Data Structures and Design: Using C++, Wiley. Johnsonbaugh, R. & Kalin, M., Object-Oriented Programming in C++, 2nd ed., Prentice Hall. 23

34 C++ and Java Self Assessment 1. An important difference between a member function and a normal function is that a member function incorporates a membership. a. identify label in the header b. c. d. identify label in the body object label in the header structure label in the header Which of the following statements is false? a. A class is a way to bind the data and its associated functions together. b. The class body contains the declaration of variables and functions. c. The class members that have been declared as public can be accessed only from within the class. d. Once a class has been declared, we can create variables of that type by using the class name. The type and scope of each member variable must be defined outside the class definition. a. static b. const c. default d. private If a member function does not alter any data in the class, then we may declare it as a. a. const data function b. static member function c. const member function d. const member The function of constructor is to. a. initialise the members of its class b. initialise the objects of its functions c. declare the objects of its class d. initialise the objects of its class The data of a class can be accessed only through the member functions of that class. a. public b. private c. static d. dynamic a user-defined data type with a template that serves to define its data properties. a. Structure b. Class c. Method d. Object 24

35 8. 9. Which of the following statements is true? a. A destructor takes any argument and returns any value. b. c. d. It is bad a practice to declare destructors in a program since it releases memory space for future use. Copy constructor initialises an object by copying the state from another object of the same class. The constructor is invoked whenever an object of its associated class is destroyed. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a. a. member b. c. d. function object tilde 10. A constructor that accepts no parameters is called the constructor. a. copy b. default c. member d. function 25

36 C++ and Java Chapter III Inheritance and Polymorphism Aim The aim of this chapter is to: elucidate inheritance define derived classes enlist the features of inheritance Objectives The objectives of this chapter are to: discuss polymorphism explain the concept of single inheritance describe the process of defining the derived class Learning outcome At the end of this chapter, you will be able to: comprehend multiple inheritance describe single inheritance with public as well as privation derivation define inheritance 26

37 3.1 Introduction to 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 features of the base class and the programmer can choose to add new features specific to the newly created derived class. For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango, banana and orange, each of these would have its own defined features. The features of inheritance are as follows: Reusability: Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. Saves time and effort: The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed; increases program structure which results in greater reliability. Defining derived classes A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is: Class derived-class-name : visibility-mode base-class-name // // members of derived class // ; The colon indicates that the derived-class-name is derived from the base-class-name. The visibility mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. For example: class ABC: private XYZ members of ABC ; // private derivation In inheritance, some of the base class data elements and member functions are inherited into the derived class. We can add our own data and member functions and thus extend the functionality of the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for incremental program development. 3.2 Single Inheritance Let us consider a simple example to illustrate inheritance. Program below shows a base class B and a derived class D. The class B contains one private data member, one public data member, and three public member functions. The class D contains one private data member and two public member functions. Single inheritance: public # include <iostream> using namespace std; class B 27

38 C++ and Java int a; // private; not inheritable public; int b; // public; ready for inheritance void get_ab(); int get_a(void); void show_a(void); ; class D: public B // public derivation int c; public; void mul(void); void display(void); ; // void B :: get_ab(void) a=5; b=10; int B :: get_a() return a; void B :: show_a() cout << a= << a<< \n ; void D :: mul () c= b*get_a(); void D :: display () cout << a = << get_a() << \n ; cout << b = << b << \n ; cout << c = << c << \n ; // int main () D d; d.get_ab(); d.mul(); d.show_a(); d.display(); d.b = 20; d.mul(); d.display (); 28

39 return 0; Output of the program is: a=5 a=5 b=10 c = 50 a = 5 b = 20 c = 100 The class D is a public derivation of the base class B. Therefore, D inherits all the public members of B and retains their visibility. Thus, a public member of the base class B is also a public member of the derived class D. The private members of B cannot be inherited by D. The class D, in effect, will have more members than what it contains at the time of declaration as shown in the figure given below. Class D Private Section C Public Section b get_ab() Inherited from B B get_a() show_a() mul() display() Fig. 3.1 Adding more members to a class (by public derivation) The program illustrates that the objects of class D have access to all the public members of B. Let us have a look at functions show_a() and mul(): void show_a() cout << a= << a<< \n ; void mul() 29

40 C++ and Java c = b* get_a(); // c=b*a Although the data member is private in B and cannot be inherited, object of D are able to access it through an inherited member function of B. Let us now consider the case of private derivation. class B int a; public: int b; void get_ab(); void get_a(); void show_a(); ; class D: private B derivation int c; public: void mul (); void display (); ; // private The membership of the derived class D is shown in the figure given below. In private derivation, the public members of the base class become private members of the derived class. Therefore, the objects of D cannot have direct access to the public member functions of B. Class D Private Section C b get_ab() Inherited from B B get_a() show_a() Public Section mul() display() Fig. 3.2 Adding more members to a class (by private derivation) 30

41 The statements such as d.get_ab(); d.get_a(); d.show_a(); // get_ab is private // so also get_a() // and show_a() will not work. However, these functions can be used inside mul() and display() like the normal functions as shown below: void mul() get_ab(); c = b *get_a(); void display () show_a() cout << b= <<b<< \n << c = <<c<< \n\n ; // outputs value of a 3.3 Multiple Inheritance A class can inherit the attributes of two or more classes as shown in the figure given below. This is known as multiple inheritance. Multiple inheritance allow us to combine the features of several existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of another. B-1 B-2 B-n D Fig. 3.3 Multiple Inheritance The syntax of a derived class with multiple base classes is as follows: class D: visibility B-1, visibility B (body of D). ; 31

42 C++ and Java where, visibility may be either public or private. The base classes are separated by commas. For example: class P: public M, public N public: void display(void); ; Classes M and N have been specified as follows: class M protected: int m; public : void get_m(int); ; void M :: get_m(int x) m = x; class N protected: int n; public: void get_n(int); ; void N :: get_n(int y) n=y; As declared above, the derived class P would, in effect, contain all the members of M and N in addition to its own members as shown below: class P protected // from M // from N public: ; // from M // from N // own member The member function display() can be defined as follows: void P:: display(void) cout << m= <<m<< \n ; 32

43 ; cout << n= <<n<< \n ; cout << m*n= <<m*n<< \n ; The main() function which provides the user-interface may be written as follows: main() Pp; p.get_m(10); p.get_n(20); p.display(); Program below shows the entire code illustrating how all the three classes are implemented in multiple inheritance mode. # include <iostream> Using namespace std; class M protected: int m; public: void get_m(int); ; class N protected: int n; public: void get_n(int); ; class P : public M, public N public: void display(void); ; void M :: get_m(int x) m = x; void N :: get_n(int y) n=y ; void P :: display(void) cout << m= << m<< \n ; 33

44 C++ and Java cout << n= << n<< \n ; cout << m*n = << m*n<< \n ; int main () P p; p.get_m(10); p.get_m(20); p.display(); return 0; Output of program is: m = 10 n = 20 m*n = Polymorphism Polymorphism is one of the crucial features of object oriented programming. It simply means one name, multiple forms. The concept of polymorphism is implemented using the overloaded functions and operators. The overloaded member functions are selected for invoking by matching arguments, both type and number. This information is known to compiler at the compile time and, therefore, compiler is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism, early binding simply means that an object is bound to its function call at compile time. Now let us consider a situation where the function name and prototype is the name in both the base and derived classes, for example, consider the following class definitions: class A int x; public: void show (). ; class B : public A int y; public: ; void shoe () // show () in base class // show () in derived class How do we use the member function show() to print the values of objects of both the classes A and B? Since the prototype of show() is the same in both the places, the function is not overloaded and therefore, static binding does not apply. In such situations, we may use the class resolution operator to specify the class while invoking the functions with the derived class objects. If the appropriate member function is selected while the program is running is known as run time polymorphism. It happens with the mechanism known as virtual function as shown in the figure given below. 34

45 Polymorphism Compile time polymorphism Run time polymorphism Function overloading Operator Overloading Virtual functions Fig. 3.4 Polymorphism At run time, when it is known which class objects are under consideration, the appropriate version of the function is invoked. Since the function is linked with a particular class much later after the compilation, this process is termed as late binding. It is also known as dynamic binding because the selection of the appropriate function is done dynamically at run time. 35

46 C++ and Java Summary 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 features of the base class and the programmer can choose to add new features specific to the newly created derived class. Features of inheritance: reusability, saves time and effort, and increases program structure which results in greater reliability. A derived class can be defined by specifying its relationship with the base class in addition to its own details. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. In inheritance, some of the base class data elements and member functions are inherited into the derived class. A class can inherit the attributes of two or more classes this is known as multiple inheritance. Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new classes. Polymorphism is one of the crucial features of object oriented programming. It simply means one name, multiple forms. The concept of polymorphism is implemented using the overloaded functions and operators. If the appropriate member function is selected while the program is running is known as run time polymorphism. References Balaguruswamy, E., Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill. Keogh, J., Object Oriented Programming: Principles and Fundamentals, Dreamtech Press. Pitts, R. I., Introduction to Polymorphism in C++ [Online] Available at: < cpp/polymorphism/intro/>[accessed 3 November 2011]. Tenoul.com, C++ Object Oriented: Readme First [Online] Available at: < cplusplustutorial.html> [Accessed 3 November 2011]. Xoax.net, C++ Console Lesson 38: Simple Inheritance [Video Online] Available at: < com/watch?v=uirdaffnr2u> [Accessed 3 November 2011]. Xoax.net, C++ Console Lesson 42: Virtual Member Functions Video Online] Available at: < youtube.com/watch?v=xxr9fbs8g4q > [Accessed 3 November 2011]. Recommended Reading Josuttis, N. M., Object-Oriented Programming in C++, 1st ed., Wiley. Kak, A., Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java, 1st ed., Wiley-IEEE Press. Farrell, J., Object-Oriented Programming Using C++, 4th ed., Cengage Learning. 36

47 Self Assessment 1. The concept of polymorphism is implemented using the functions and operators. a. overridden b. overloaded c. object oriented d. inherited Multiple inheritance allows us to combine the features of several existing classes as a starting point for defining new. a. objects b. c. d. functions classes methods Which of the following statements is false? a. Inheritance means one name, multiple forms. b. c. d. A derived class can be defined by specifying its relationship with the base class in addition to its own details. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. In inheritance, some of the base class data elements and member functions are inherited into the derived class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for program development. a. incremental b. c. d. existing object oriented implementing If the appropriate function is selected while the program is running is known as run time polymorphism. a. class b. c. d. object member derived A class can be defined by specifying its relationship with the base class in addition to its own details. a. base b. c. d. derived member function 37

48 C++ and Java is the process by which new classes called derived classes are created from existing classes called base classes a. Inheritance b. c. d. Exception Polymorphism Binding Which of the following statements is true? a. We can delete our own data and member functions and thus extend the functionality of the base class. b. c. d. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very dynamic tool for incremental program development. Inheritance decreases program structure which results in greater reliability The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. Early binding simply means that an object is bound to its function call at. a. compile time b. c. d. run time error time development time 10. mode specifies whether the features of the base class are privately derived or publicly derived. a. Dynamic b. Static c. Visibility d. Development 38

49 Chapter IV Templates and Exception Handling Aim The aim of this chapter is to: introduce the concept of templates analyse the sequence of events when the exception occurs discuss the simple function template Objectives The objectives of this chapter are to: describe class templates explain the concept of exceptions discuss the process of throwing an exception Learning outcome At the end of this chapter, you will be able to: discuss function templates justify the need of exceptions comprehend class template 39

50 C++ and Java 4.1 Introduction to Templates A template enables us to define generic classes and functions and thus provides support for generic programming. A template can be used to create a family of classes or functions. For example, a class template for an array class would enable us to create arrays of various data types such as int array and float array. A template can be considered as a kind of macro. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are sometimes called parameterised classes or functions. The template concept can be used in two different ways: Functions Classes 4.2 Function Templates Suppose we want to write a function that returns the absolute value of two numbers. As we remember from high school algebra, the absolute value of a number is its value without regard to its sign. The absolute value of 3 is 3, and the absolute value of 3 is also 3. Ordinarily, this function would be written for a particular data type: int abs(int n) //absolute value of ints return (n<0)? -n : n; //if n is negative, return -n Here, the function is defined to take an argument of type int and to return a value of this same type. But now suppose we want to find the absolute value of a type long. We will need to write a completely new function: long abs(long n) //absolute value of longs return (n<0)? -n : n; And again, for type float: float abs(float n) //absolute value of floats return (n<0)? -n : n; The body of the function is written the same way in each case, but they are completely different functions because they handle arguments and return values of different types. It is true that in C++, these functions can all be overloaded to have the same name, but nevertheless, we must write a separate definition for each one. Rewriting the same function body over and over for different types is time consuming and wastes space in the listing. Also, if we find an error in one such function, it needs to be corrected in each function body. Failing to do this correctly, introduce inconsistencies into the program. It would be nice if there was a way to write such a function just once, and have it work for many different data types A Simple Function Template Our first example shows how to write our absolute-value function as a template, so that it will work with any basic numerical type. This program defines a template version of abs() and then, in main(), invokes this function with different data types to prove that it works. Here is the listing for TEMPABS: // tempabs.cpp // template used for absolute value function #include <iostream> using namespace std; //

51 template <class T> //function template T abs(t n) return (n < 0)? -n : n; // int main() int int1 = 5; int int2 = -6; long lon1 = 70000L; long lon2 = L; double dub1 = 9.95; double dub2 = ; //calls instantiate functions cout << \nabs( << int1 << )= << abs(int1); //abs(int) cout << \nabs( << int2 << )= << abs(int2); //abs(int) cout << \nabs( << lon1 << )= << abs(lon1); //abs(long) cout << \nabs( << lon2 << )= << abs(lon2); //abs(long) cout << \nabs( << dub1 << )= << abs(dub1); //abs(double) cout << \nabs( << dub2 << )= << abs(dub2); //abs(double) cout << endl; return 0; Output of the program is: abs(5)=5 abs(-6)=6 abs(70000)=70000 abs(-80000)=80000 abs(9.95)=9.95 abs(-10.15)=10.15 As we can see, the abs() function now works with all three of the data types (int, long, and double) that we use as arguments. It will work on other basic numerical types as well, and it will even work on user-defined data types, provided that the less-than operator (<) and the unary minus operator (-) are appropriately overloaded. Here is how we specify the abs() function to work with multiple data types: template <class T> //function template T abs(t n) return (n<0)? -n : n; This entire syntax, with a first line starting with the keyword template and the function definition following, is called a function template. 4.3 Class Templates The template concept can be extended to classes. Class templates are generally used for data storage (container) classes. Stacks and linked lists are examples of data storage classes. class Stack private: int st[max]; //array of ints 41

52 C++ and Java int top; //index number of top of stack public: Stack(); //constructor void push(int var); //takes int as argument int pop(); //returns int value ; If we wanted to store data of type long in a stack, we would need to define a completely new class: class LongStack private: long st[max]; //array of longs int top; //index number of top of stack public: LongStack(); //constructor void push(long var); //takes long as argument long pop(); //returns long value ; Similarly, we would need to create a new stack class for every data type we wanted to store. It would be nice to be able to write a single class specification that would work for variables of all types, instead of a single basic type. As we know, class templates allow us to do this. We will create a variation of STAKARAY that uses a class template. Here is the listing for TEMPSTAK: // tempstak.cpp // implements stack class as a template #include <iostream.h> using namespace std; const int MAX = 100; //size of array //////////////////////////////////////////////////////////////// template <class Type> class Stack private: Type st[max]; //stack: array of any type int top; //number of top of stack public: Stack() //constructor top = -1; void push(type var) //put number on stack st[++top] = var; Type pop() //take number off stack return st[top--]; ; //////////////////////////////////////////////////////////////// int main() Stack<float> s1; //s1 is object of class Stack<float> s1.push(1111.1f); //push 3 floats, pop 3 floats s1.push(2222.2f); s1.push(3333.3f); cout << 1: << s1.pop() << endl; cout << 2: << s1.pop() << endl; cout << 3: << s1.pop() << endl; 42

53 Stack<long> s2; //s2 is object of class Stack<long> s2.push( l); //push 3 longs, pop 3 longs s2.push( l); s2.push( l); cout << 1: << s2.pop() << endl; cout << 2: << s2.pop() << endl; cout << 3: << s2.pop() << endl; return 0; Here, the class Stack is presented as a template class. The approach is similar to that used in function templates. The template keyword and class Stack signal that the entire class will be a template. template <class Type> class Stack //data and member functions using template argument Type ; A template argument, named Type in this example, is then used (instead of a fixed data type like int) every place in the class specification where there is a reference to the type of the array st. There are three such places: the definition of st, the argument type of the push() function, and the return type of the pop() function. Class templates differ from function templates in the way they are instantiated. To create an actual function from a function template, we call it using arguments of a specific type. Classes, however, are instantiated by defining an object using the template argument. Stack<float> s1; This creates an object, s1, a stack that stores numbers of type float. The compiler provides space in memory for this object s data, using type float wherever the template argument Type appears in the class specification. It also provides space for the member functions (if these have not already been placed in memory by another object of type Stack<float>). These member functions also operate exclusively on type float. Creating a Stack object that stores objects of a different type, as in Stack<long> s2; creates not only a different space for data, but also a new set of member functions that operate on type long. Note, that the name of the type of s1 consists of the class name Stack plus the template argument: Stack<float>. This distinguishes it from other classes that might be created from the same template, such as Stack<int> or Stack<long>. In TEMPSTAK, we exercise the s1 and s2 stacks by pushing and popping three values on each one and displaying each popped value. Here is the output: 1: //float stack 2: : : //long stack 2: : In this example, the template approach gives us two classes for the price of one, and we could instantiate class objects for other numerical types with just a single line of code. 43

54 C++ and Java 4.4 Exceptions Exceptions provide a systematic, object-oriented approach to handling run-time errors generated by C++ classes. Exceptions are errors that occur at run time. They are caused by a wide variety exceptional circumstance, such as running out of memory, not being able to open a file, trying to initialise an object to an impossible value, or using an out-of-bounds index to a vector. Why do we need exceptions? Why do we need a new mechanism to handle errors? Let us look at how the process was handled in the past. In C-language programs, an error is often signalled by returning a particular value from the function in which it occurred. For example, disk-file functions often return NULL or 0 to signal an error. Each time we call one of these functions, you check the return value: if( somefunc() == ERROR_RETURN_VALUE ) //handle the error or call error-handler function else //proceed normally if( anotherfunc() == NULL ) //handle the error or call error-handler function else //proceed normally if( thirdfunc() == 0 ) //handle the error or call error-handler function else //proceed normally One problem with this approach is that every single call to such a function must be examined by the program. Surrounding each function call with an if...else statement, and adding statements to handle the error (or call an errorhandler routine), requires a lot of code and makes the listing convoluted and hard to read. The problem becomes more complex when classes are used, since errors may take place without a function being explicitly called. For example, suppose an application defines objects of a class: SomeClass obj1, obj2, obj3; How will the application find out if an error occurred in the class constructor? The constructor is called implicitly, so there is no return value to be checked. Things are complicated even further when an application uses class libraries. A class library and the application that makes use of it are often created by separate people: the class library by a vendor and the application by a programmer who buys the class library. This makes it even harder to arrange for error values to be communicated from a class member function to the program that is calling the function. The problem of communicating errors from deep within class libraries is probably the most important problem solved by exceptions Exception Syntax Imagine an application that creates and interacts with objects of a certain class. Ordinarily the application s calls to the class member functions cause no problems. Sometimes, however, the application makes a mistake, causing an error to be detected in a member function. This member function then informs the application that an error has occurred. When exceptions are used, this is called throwing an exception. In the application, we install a separate section of code to handle the error. This code is called an exception handler or catch block; it catches the exceptions thrown by the member function. Any code in the application that uses objects of the class is enclosed in a try block. Errors generated in the try block will be caught in the catch block. Code that does not interact with the class need not be in a try block. The exception mechanism uses three new C++ keywords: throw, catch and try. Also, we need to create a new kind of entity called an exception class. XSYNTAX is not a working program, but a skeleton program to show the syntax. 44

55 // xsyntax.cpp // not a working program //////////////////////////////////////////////////////////////// class AClass //a class public: class AnError //exception class ; void Func() //a member function if( /* error condition */ ) throw AnError(); //throw exception ; //////////////////////////////////////////////////////////////// int main() //application try //try block AClass obj1; //interact with AClass objects obj1.func(); //may cause error catch(aclass::anerror) //exception handler //(catch block) //tell user about error, etc. return 0; We start with a class called AClass, which represents any class in which errors might occur. An exception class, AnError is specified in the public part of AClass. In AClass s member functions, we check for errors. If we find one, we throw an exception, using the keyword throw followed by the constructor for the error class: throw AnError(); // throw followed by constructor for AnError class In the main() part of the program, we enclose any statements that interact with AClass in a try block. If any of these statements causes an error to be detected in an AClass member function, an exception will be thrown and control will go to the catch block that immediately follows the try block. A simple exception example Let us look at a working program example that uses exceptions. The application program might attempt to push too many objects onto the stack, thus exceeding the capacity of the array, or it might try to pop too many objects off the stack, thus obtaining invalid data. In the XSTAK program we use an exception to handle these two errors. // xstak.cpp // demonstrates exceptions #include <iostream> using namespace std; const int MAX = 3; //stack holds 3 integerss //////////////////////////////////////////////////////////////// class Stack private: 45

56 C++ and Java int st[max]; //array of integers int top; //index of top of stack public: class Range //exception class for Stack //note: empty class body ; Stack() //constructor top = -1; void push(int var) if(top >= MAX-1) throw Range(); st[++top] = var; int pop() if(top < 0) throw Range(); return st[top--]; //if stack full, //throw exception //put number on stack //if stack empty, //throw exception //take number off stack ; //////////////////////////////////////////////////////////////// int main() Stack s1; try s1.push(11); s1.push(22); s1.push(33); // s1.push(44); //oops: stack full cout << 1: << s1.pop() << endl; cout << 2: << s1.pop() << endl; cout << 3: << s1.pop() << endl; cout << 4: << s1.pop() << endl; //oops: stack empty catch(stack::range) //exception handler cout << Exception: Stack Full or Empty << endl; cout << Arrive here after catch (or normal exit) << endl; return 0; Note that we have made the stack small so that it is easier to trigger an exception by pushing too many items. Let us examine the features of this program that deal with exceptions. There are four of them. In the class specification, there is an exception class. There are also statements that throw exceptions. In the main() part of the program, there is a block of code that may cause exceptions (the try block), and a block of code that handles the exception (the catch block). 46

57 Specifying the exception class The program first specifies an exception class within the Stack class: class Range //note: empty class body ; Here the body of the class is empty, so objects of this class have no data and no member functions. All we really need in this simple example is the class name, Range. This name is used to connect a throw statement with a catch block Throwing an Exception In the Stack class, an exception occurs if the application tries to pop a value when the stack is empty or tries to push a value when the stack is full. To let the application know that it has made such a mistake when manipulating a Stack object, the member functions of the Stack class check for these conditions using if statements, and throw an exception if they occur. In XSTAK, the exception is thrown in two places, both using the statement: throw Range(); The Range() part of this statement invokes the (implicit) constructor for the Range class, which creates an object of this class. The throw part of the statement transfers program control to the exception handler. The try block All the statements in main() that might cause this exception, i.e., statements that manipulate Stack objects, are enclosed in braces and preceded by the try keyword: try //code that operates on objects that might cause an exception This is simply part of the application s normal code; it is what we would need to write even if we are not using exceptions. Not all the code in the program needs to be in a try block; just the code that interacts with the Stack class. Also, there can be many try blocks in our program, so we can access Stack objects from different places. The exception handler (catch block) The code that handles the exception is enclosed in braces, preceded by the catch keyword, with the exception class name in parentheses. The exception class name must include the class in which it is located. Here it is Stack::Range. catch(stack::range) //code that handles the exception This construction is called the exception handler. It must immediately follow the try block. In xstak the exception handler simply prints an error message to let the user know why the program failed. Control falls through the bottom of the exception handler, so we can continue processing at that point. Or the exception handler may transfer control elsewhere, or (often) terminate the program. 47

58 C++ and Java Sequence of events Let us summarise the sequence of events when an exception occurs. Code is executing normally outside a try block. Control enters the try block. A statement in the try block causes an error in a member function. The member function throws an exception. Control transfers to the exception handler (catch block) following the try block. Notice how clean the resulting code is. Any of the statements in the try block could cause an exception, but we don t need to worry about checking a return value for each one, because the try-throw-catch arrangement handles them all automatically. In this particular example we have deliberately created two statements that cause exceptions. The first, s1.push(44); //pushes too many items causes an exception if you remove the comment symbol preceding it, and the second, cout << 4: << s1.pop() << endl; //pops item from empty stack causes an exception if the first statement is commented out. Try it each way. In both cases, the same error message will be displayed: Stack Full or Empty Initialising an exception object How do we initialise the data when we throw an exception? In the two-argument constructor for the Stack class we say: throw InchesEx( 2-arg constructor, in); and in the getdist() nmember function for Stack it is throw InchesEx( getdist() function, inches); When the exception is thrown, the handler will display the string and inches values. The string will tell us which member function is throwing the exception, and the value of inches will report the faulty inches value detected by the member function. This additional data will make it easier for the programmer or user to figure out what caused the error Handling Exceptions After we catch an exception, we will sometimes want to terminate our application. The exception mechanism gives us a chance to indicate the source of the error to the user, and to perform any necessary clean-up chores before terminating. It also makes clean-up easier by executing the destructors for objects created in the try block. This allows us to release system resources, such as memory, that such objects may be using. In other cases, we will not want to terminate the program. Perhaps our program can figure out what caused the error and correct it, or the user can be asked to input different data. When this is the case, the try and catch blocks are typically embedded in a loop, so control can be returned to the beginning of the try block (which the exception mechanism has attempted to restore to its initial state). If there is no exception handler that matches the exception thrown, the program is unceremoniously terminated by the operating system. 48

59 Summary A template enables us to define generic classes and functions and thus provides support for generic programming. A template can be used to create a family of classes or functions. Since a template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or function, the templates are sometimes called parameterised classes or functions. The template concept can be used in two different ways: functions, and classes. The body of the function is written the same way in each case, but they are completely different functions because they handle arguments and return values of different types. It is true that in C++ these functions can all be overloaded to have the same name, but we must nevertheless write a separate definition for each one. Class templates are generally used for data storage (container) classes. Class templates differ from function templates in the way they are instantiated. To create an actual function from a function template, we call it using arguments of a specific type. Classes, however, are instantiated by defining an object using the template argument. Exceptions provide a systematic, object-oriented approach to handling run-time errors generated by C++ classes. Exceptions are errors that occur at run time. The problem of communicating errors from deep within class libraries is probably the most important problem solved by exceptions. The exception mechanism uses three new C++ keywords: throw, catch, and try. The exception mechanism gives us a chance to indicate the source of the error to the user, and to perform any necessary clean-up chores before terminating. If there is no exception handler that matches the exception thrown, the program is unceremoniously terminated by the operating system References Msdn.microsoft.com, C++ Exception Handling [Online] Available at: < library/4t3saedz.aspx> [Accessed 3 November 2011] Balaguruswamy, E., Object Oriented Programming with C++, 3rd ed., Tata McGraw Hill. Venugopal, K. R., Mastering C++, Muhammadali Shaduli. Williams, A., Introduction to C++ Templates [pdf] Available at: < articles/intrototemplates.pdf> [Accessed 3 November 2011]. Xoax.net, C++ Console Lesson 19: Function Templates [Video Online] Available at: < com/watch?v=0e1ia9wfpnq> [Accessed 3 November 2011]. VTC, C++ Fundamentals: 51. Exception Handling [Video Online] Available at: < com/watch?v=mmgec3angz8&feature=results_video&playnext=1&list=plb08c597637c40fc4> [Accessed 3 November 2011]. Recommended Reading Skinner, M. T., The advanced C++ book: Volume 1. Silicon Press. Lafore, R., Object Oriented Programming in C++, 3rd ed., Macmillan Computer Publishing. Stroustrup, B., The C++ Programming Language: Special Edition, 3rd ed., Addison-Wesley Professional. 49

60 C++ and Java Self Assessment 1. To create an actual function from a function template, we call it using of a specific type. a. arguments b. data c. members d. source Exceptions provide a systematic, object-oriented approach to handling errors generated by C++ classes. a. compile b. c. d. run-time coding data In language programs, an error is often signaled by returning a particular value from the function in which it occurred. a. Java b. c. d. C C++ Cobol The exception mechanism gives us a chance to indicate the source of the error to the user, and to perform any necessary. a. clean-up chores before running b. c. d. clean-up chores before starting run-time chores before terminating clean-up chores before terminating Class templates are generally used for data classes. a. clean-up b. c. d. terminating storage error Which of the following statements is false? a. The exception class name must include the object in which it is located. b. c. d. Any code in the application that uses objects of the class is enclosed in a try block. Exceptions are errors that occur at run time. Class templates differ from function templates in the way they are instantiated. If there is no exception handler that matches the exception thrown, the program is unceremoniously by the operating system. a. compiled b. c. d. instantiated located terminated 50

61 8. 9. Which of the following is the most important problem solved by exceptions? a. Communicating errors from deep within class libraries b. c. d. To perform any necessary clean-up chores To worry about checking a return value To let the user know why the program failed A enables us to define generic classes and functions and thus provides support for generic programming. a. program b. c. d. function object template 10. A template can be considered as a kind of. a. program b. data file c. macro d. class 51

62 C++ and Java Chapter V Introduction to JAVA Aim The aim of this chapter is to: introduce the concept of Java explain the concept of polymorphism in Java compare Java with other languages Objectives The objectives of this chapter are to: discuss history of Java explain the concept of virtual machine enumerate the types concept in Java Learning outcome At the end of this chapter, you will be able to: understand the concept of inheritance in Java describe virtual machine define encapsulation in Java 52

63 5.1 Concept of Java The Java programming language, developed at Sun Microsystems under the guidance of Net luminaries James Gosling and Bill Joy, is designed to be a machine-independent programming language that is both safe enough to traverse networks and powerful enough to replace native executable code. Java addresses the issues raised here and may help us start building the kinds of applications we want. Initially, most of the enthusiasm for Java centered on its capabilities for building embedded applications for the World Wide Web; these applications are called applets. Applets could be independent programs in themselves, or sophisticated frontends to programs running on a server. More recently, interest has shifted to other areas. With Java 2, Java has the most sophisticated toolkit for building graphical user interfaces; this development has allowed Java to become a popular platform for developing traditional application software. Java has also become an important platform for server-side applications, using the servlet interface, and for enterprise applications using technologies such as Enterprise JavaBean. And Java is the platform of choice for modern distributed applications. 5.2 Origin of Java The seeds of Java were planted in 1990 by Sun Microsystems patriarch and chief researcher, Bill Joy. Since, Sun s inception in the early 80s, it has steadily pushed one idea the network is the computer. At the time though, Sun was competing in a relatively small workstation market, while Microsoft was beginning its domination of the more mainstream, Intel-based PC world. When Sun missed the boat on the PC revolution, Joy retreated to Aspen, Colorado, to work on advanced research. He was committed to accomplish complex tasks with simple software, and founded the aptly named Sun Aspen Smallworks. Of the original members of the small team of programmers assembled in Aspen, James Gosling is the one who will be remembered as the father of Java. Gosling first made a name for himself in the early 80 s as the author of Gosling Emacs, the first version of the popular Emacs editor that was written in C and ran under Unix. Gosling Emacs became popular, but was soon eclipsed by a free version, GNU Emacs, written by Emacs s original designer. By that time, Gosling had moved on to design Sun s NeWS window system, which briefly contended with the X Window System for control of the UNIX graphical user interface (GUI) desktop in While some people would argue that NeWS was superior to X, NeWS lost out because Sun kept it proprietary and didn t publish source code, while the primary developers of X formed the X Consortium and took the opposite approach. Designing NeWS taught Gosling the power of integrating an expressive language with a networkaware windowing GUI. It also taught Sun that the Internet programming community will refuse to accept proprietary standards, no matter how good they may be. The seeds of Java s remarkably permissive licensing scheme were sown by NeWS s failure. Gosling brought what he had learned to Bill Joy s nascent Aspen project, and in 1992, work on the project led to the founding of the Sun subsidiary, FirstPerson, Inc. Its mission was to lead Sun into the world of consumer electronics. The FirstPerson team worked on developing software for information appliances, such as cellular phones and personal digital assistants (PDAs). The goal was to enable the transfer of information and real-time applications over cheap infrared and packet- based networks. Memory and bandwidth limitations dictated small and efficient code. The nature of the applications also demanded they be safe and robust. Gosling and his teammates began programming in C++, but they soon found themselves confounded by a language that was too complex, unwieldy, and insecure for the task. They decided to start from scratch, and Gosling began working on something he dubbed C++ minus minus. 53

64 C++ and Java With the foundering of the Apple Newton, it became apparent that the PDA s ship had not yet come in, so Sun shifted First Person s efforts to interactive TV (ITV). The programming language of choice for ITV set-top boxes was the near ancestor of Java, a language called Oak. Even with its elegance and ability to provide safe interactivity, Oak could not salvage the lost cause of ITV. Customers didn t want it, and Sun soon abandoned the concept. At that time, Joy and Gosling got together to decide on a new strategy for their language. It was 1993, and the explosion of interest in the Internet, and the World Wide Web in particular, presented a new opportunity. Oak was small, robust, architecture-independent, and object-oriented. As it happens, these are also the requirements for a universal, network-savvy Programming language. Sun quickly changed focus, and with a little retooling, Oak became Java. 5.3 A Virtual Machine Java is both a compiled and an interpreted language. Java source code is turned into simple binary instructions, much like ordinary microprocessor machine code. However, whereas C or C++ source is refined to native instructions for a particular model of processor, Java source is compiled into universal format instructions for a virtual machine. Compiled Java byte-code, also called J-code, is executed by a Java runtime interpreter. The runtime system performs all the normal activities of a real processor, but it does so in a safe, virtual environment. It executes the stack-based instruction set and manages a storage heap. It creates and manipulates primitive data types, and loads and invokes newly referenced blocks of code. Most importantly, it does all this in accordance with a strictly defined open specification that can be implemented by anyone who wants to produce a Java-compliant virtual machine. Together, the virtual machine and language definition provide a complete specification. There are no features of Java left undefined or implementation-dependent. For example, Java specifies the sizes of all its primitive data types, rather than leave it up to each implementation. The Java interpreter is relatively lightweight and small; it can be implemented in whatever form is desirable for a particular platform. On most systems, the interpreter is written in a fast, natively compiled language such as C or C++. The interpreter can be run as a separate application, or it can be embedded in another piece of software, such as a web browser. All of this means that Java code is implicitly portable. The same Java application byte-code can run on any platform that provides a Java runtime environment, as shown in the figure below. You don t have to produce alternative versions of your application for different platforms, and you don t have to distribute source code to end users. Source Code Java runtime Byte Code Unix PC Macintosh Fig. 5.1 The Java runtime environment 54

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

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

PROGRAMMING IN C++ COURSE CONTENT

PROGRAMMING IN C++ COURSE CONTENT PROGRAMMING IN C++ 1 COURSE CONTENT UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 2 1.1 Procedure oriented Programming 1.2 Object oriented programming paradigm 1.3 Basic concepts of Object Oriented

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

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

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

Object Oriented Programming. C++ 6 th Sem, A Div Ms. Mouna M. Naravani

Object Oriented Programming. C++ 6 th Sem, A Div Ms. Mouna M. Naravani Object Oriented Programming C++ 6 th Sem, A Div 2018-19 Ms. Mouna M. Naravani Object Oriented Programming (OOP) removes some of the flaws encountered in POP. In OOPs, the primary focus is on data rather

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

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

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

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

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

B.C.A 2017 OBJECT ORIENTED PROGRAMMING USING C++ BCA303T MODULE SPECIFICATION SHEET

B.C.A 2017 OBJECT ORIENTED PROGRAMMING USING C++ BCA303T MODULE SPECIFICATION SHEET B.C.A 2017 OBJECT ORIENTED PROGRAMMING USING C++ BCA303T MODULE SPECIFICATION SHEET Course Outline The main objective of this course is to introduce students to the basic concepts of a selected language

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

Object Oriented Pragramming (22316)

Object Oriented Pragramming (22316) Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data

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

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

CS6301 PROGRAMMING AND DATA STRUCTURES II QUESTION BANK UNIT-I 2-marks ) Give some characteristics of procedure-oriented language. Emphasis is on doing things (algorithms). Larger programs are divided

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

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

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT I INTRODUCTION TO OOP AND FUNDAMENTALS OF JAVA 1. Define OOP. Part A Object-Oriented Programming (OOP) is a methodology or paradigm to design a program using classes and objects. It simplifies the

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

An Object Oriented Programming with C

An Object Oriented Programming with C An Object Oriented Programming with C By Tanmay Kasbe Dr. Ravi Singh Pippal IDEA PUBLISHING WWW.ideapublishing.in i Publishing-in-support-of, IDEA PUBLISHING Block- 9b, Transit Flats, Hudco Place Extension

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

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More 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

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

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

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

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

(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

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING 1. Programming Paradigms OBJECT ORIENTED PROGRAMMING A programming methodology defines the methodology of designing and implementing programs using the key features and other building blocks (such as key

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

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

C++ & Object Oriented Programming Concepts The procedural programming is the standard approach used in many traditional computer languages such as BASIC, C, FORTRAN and PASCAL. The procedural programming

More information

#include <iostream> #include <cstdlib>

#include <iostream> #include <cstdlib> Classes and Objects Classes The structure data type can be used in both C and C++ Usually a structure is used to store just data, however it can also be used to store functions that can work on the data.

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

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

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

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

Programmiersprachen (Programming Languages)

Programmiersprachen (Programming Languages) 2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html

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

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

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 1 Date:

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful?

Organization of Programming Languages (CSE452) Why are there so many programming languages? What makes a language successful? Organization of Programming Languages (CSE452) Instructor: Dr. B. Cheng Fall 2004 1 Why are there so many programming languages? Evolution -- we've learned better ways of doing things over time Socio-economic

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

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

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

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

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

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

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1 Chapter -1 1. Object Oriented programming is a way of problem solving by combining data and operation 2.The group of data and operation are termed as object. 3.An object is a group of related function

More information

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques

Spring 2003 Instructor: Dr. Shahadat Hossain. Administrative Matters Course Information Introduction to Programming Techniques 1 CPSC2620 Advanced Programming Spring 2003 Instructor: Dr. Shahadat Hossain 2 Today s Agenda Administrative Matters Course Information Introduction to Programming Techniques 3 Course Assessment Lectures:

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

10. Abstract Data Types

10. Abstract Data Types 10. Abstract Data Types 11.1 The Concept of Abstraction The concept of abstraction is fundamental in programming Nearly all programming languages support process abstraction with subprograms Nearly all

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space.

The object-oriented approach goes a step further by providing tools for the programmer to represent elements in the problem space. 1 All programming languages provide abstractions. Assembly language is a small abstraction of the underlying machine. Many imperative languages (FORTRAN, BASIC, and C) are abstractions of assembly language.

More information

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

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

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

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

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

Syllabus for Bachelor of Technology. Computer Engineering. Subject Code: 01CE1303. B.Tech. Year - II

Syllabus for Bachelor of Technology. Computer Engineering. Subject Code: 01CE1303. B.Tech. Year - II Subject Code: 01CE1303 Subject Name: Object Oriented Design and Programming B.Tech. Year - II Objective: The objectives of the course are to have students identify and practice the object-oriented programming

More information

Partha Sarathi Mandal

Partha Sarathi Mandal MA 253: Data Structures Lab with OOP Tutorial 1 http://www.iitg.ernet.in/psm/indexing_ma253/y13/index.html Partha Sarathi Mandal psm@iitg.ernet.in Dept. of Mathematics, IIT Guwahati Reference Books Cormen,

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

Object Oriented Programming(OOP).

Object Oriented Programming(OOP). Object Oriented Programming(OOP). OOP terminology: Class : A class is a way to bind data and its associated function together. It allows the data to be hidden. class Crectangle Data members length; breadth;

More information

Chapter 10 :: Data Abstraction and Object Orientation

Chapter 10 :: Data Abstraction and Object Orientation Chapter 10 :: Data Abstraction and Object Orientation Programming Language Pragmatics, Fourth Edition Michael L. Scott Copyright 2016 Elsevier Chapter10_Data_Abstraction_and_Object_Orientation_4e 1 Object-Oriented

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

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

Object Oriented Programming through Java

Object Oriented Programming through Java Object Oriented Programming through Java Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune Prof. M. K. Ghadoliya

More information

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING

DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING DHANALAKSHMI COLLEGE OF ENGINEERING, CHENNAI DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING CS6456 OBJECT ORIENTED PROGRAMMING Unit I : OVERVIEW PART A (2 Marks) 1. Give some characteristics of procedure-oriented

More information

Today s lecture. CS 314 fall 01 C++ 1, page 1

Today s lecture. CS 314 fall 01 C++ 1, page 1 Today s lecture Midterm Thursday, October 25, 6:10-7:30pm general information, conflicts Object oriented programming Abstract data types (ADT) Object oriented design C++ classes CS 314 fall 01 C++ 1, page

More information

C++ Programming Fundamentals

C++ Programming Fundamentals C++ Programming Fundamentals 269 Elvis C. Foster Lecture 11: Templates One of the contemporary sophistries of C++ programming is defining and manipulating templates. This lecture focuses on this topic.

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

Advantages of Object Oriented Programming :- Features of Object Oriented Programming :- Advantages Of Object Oriented Programming :

Advantages of Object Oriented Programming :- Features of Object Oriented Programming :- Advantages Of Object Oriented Programming : Advantages of Object Oriented Programming :- 1. Exploits the expressive power of all object oriented programming languages. 2. Encourages the resuse of software components. 3. Leads to the systems that

More information

Darshan Institute of Engineering & Technology for Diploma Studies

Darshan Institute of Engineering & Technology for Diploma Studies 1. Explain Call by Value vs. Call by Reference Or Write a program to interchange (swap) value of two variables. Call By Value In call by value pass value, when we call the function. And copy this value

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

COIMBATORE EDUCATIONAL DISTRICT

COIMBATORE EDUCATIONAL DISTRICT COIMBATORE EDUCATIONAL DISTRICT REVISION EXAMINATION JANUARY 2015 STD-12 COMPUTER SCIENCE ANSEWR KEY PART-I Choose the Correct Answer QNo Answer QNo Answer 1 B Absolute Cell Addressing 39 C Void 2 D

More information

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More 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

Unit 1 : Principles of object oriented programming

Unit 1 : Principles of object oriented programming Unit 1 : Principles of object oriented programming Difference Between Procedure Oriented Programming (POP) & Object Oriented Programming (OOP) Divided Into Importance Procedure Oriented Programming In

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

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1 Object-Oriented Languages and Object-Oriented Design Ghezzi&Jazayeri: OO Languages 1 What is an OO language? In Ada and Modula 2 one can define objects encapsulate a data structure and relevant operations

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

Data Structures and Programming with C++

Data Structures and Programming with C++ Data Structures and Programming with C++ By Dr. Atul Kumar Dwivedi ETC, BIT, Durg UNIT-I B. E., V Semester Outline Basic concepts of Object oriented Programming (OOPs) 1. Objects 2. Classes 3. Data encapsulation

More information