Course Code : Course Title : Assignment Number : Maximum

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Course Code : Course Title : Assignment Number : Maximum as PDF for free.

More details

  • Words: 4,605
  • Pages: 17
Course Code : Course Title : Assignment Number : Maximum Marks Last Date of Submission

CS 72 C++ and Object Oriented Programming BCA (6)-72/Assignment/ 09 : 25 : 30th October, 2009

There are eight questions in this Assignment. Answer all the questions. You may use illustrations and diagrams to enhance your explanations. Answer to each part of the question should be confined to about 300 words. Q. 1 Explain four major advantages of Object Oriented Programming with the help of an example each. (2 marks) Answer 1 .Object-oriented programming (OOP) is a programming paradigm that uses "objects" and their interactions to design applications and computer programs. Programming techniques may include features such as information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance. Object oriented programming (OOP)is well suited to describe autonomous agents,so it should have appeal to scientists and modelers on that basis alone. However, that is not the end of the subject. OOP it has virtues that are equally important to computer programmers. OOP, as it is found in Objective-C, is not exactly the same as OOP in C++ or Java, but these languages have some significant features in common. The features we emphasize here are encapsulation and inheritance. Encapsulation This has both substantive and practical implications. The substantive importance is that the representation of an individual actor now presumes that the actor is a self-contained entity and that other actors do not automatically have access to all information inside that actor. Like humans, objects have to take effort to convey information to each other about their internal states. The practical advantages of encapsulation, however, are just as important. Computer projects can be broken down into separable components (code for the classes) and when the code is finished, the details of what goes on inside each object may not be important to the programmer. For example, if an object groceryStore can respond to an message takeMoney, and it gets the job done, we might not care how it does it.

Interface Vs Implementation

This is commonly referred to as the separation of "interface" from "implementation." While the interface declares what methods the object can execute, the implementation May remain hidden (Figure), the user only has to be familiar with the interface of an Object, not it's implementation

Inheritance

Inheritance works because code for each class designates that class as a subclass of a super class. For example, in the GNU Objective-C compiler used in the Swarm project, there is a most basic class, "object". From the object class, the Swarm libraries create subclasses, and subclasses are created from them, and so forth until the programmer in a swarm project wants to create a new class of actors that is sub classes from Discrete Event Simulation A Swarm simulation proceeds in discrete time steps. Objects are created and then interact according to a scheduling mechanism. As the simulation proceeds, the agents update their instance variables and they may be asked to report their state to the observer swarm layer of the simulation. The modeling process in Swarm, then, is quite different from simulation modeling in a non-object oriented language, such as Fortran or Pascal. These so-called "procedural languages" do not allow the modeler to take advantage of reusable classes through inheritance or the preservation of data allowed by encapsulation. Here's an example of a simulation in a procedural language: Procedural language pseudo-code 1. get parameters 2. initialize[1] 3. for 1 to timesteps do: a. for 1 to num_agents do: i. agent-i-do-something [2] b. show state [3] 4. quit

Q. 2 Explain the following terms in the context of object oriented programming. Also explain how these concepts are implemented in C++ by giving an example program for each. (a) Single Inheritance (b) Abstraction (c) Encapsulation (d) Function Overloading (4 marks) Answer 2.a) Single Inheritance In "single inheritance," a common form of inheritance, classes have only one base class. Consider the relationship illustrated in the following figure. Simple Single-Inheritance Graph

Note the progression from general to specific in the figure. Another common attribute found in the design of most class hierarchies is that the derived class has a "kind of" relationship with the base class. In the figure, a Book is a kind of a PrintedDocument, and a PaperbackBook is a kind of a book. One other item of note in the figure: Book is both a derived class (from PrintedDocument) and a base class (PaperbackBook is derived from Book). A skeletal declaration of such a class hierarchy is shown in the following example: Copy Code

// deriv_SingleInheritance.cpp // compile with: /LD class PrintedDocument {}; // Book is derived from PrintedDocument. class Book : public PrintedDocument {}; // PaperbackBook is derived from Book. class PaperbackBook : public Book {}; PrintedDocument is considered a "direct base" class to Book; it is an "indirect base" class to PaperbackBook. The difference is that a direct base class appears in the base list of a class declaration and an indirect base does not. The base class from which each class is derived is declared before the declaration of the derived class. It is not sufficient to provide a forward-referencing declaration for a base class; it must be a complete declaration. In the preceding example, the access

specifier public is used. The meaning of public, protected, and private inheritance is described in Member-Access Control. A class can serve as the base class for many specific classes, as illustrated in the following figure. Sample of Directed Acyclic Graph

In the diagram shown above, called a "directed acyclic graph" (or "DAG"), some of the classes are base classes for more than one derived class. However, the reverse is not true: there is only one direct base class for any given derived class. The graph in the figure depicts a "single inheritance" structure. b).Abstraction Abstraction is the process or result of generalization by reducing the information content of a concept or an observable phenomenon, typically in order to retain only information which is relevant for a particular purpose. For example, abstracting a leather soccer ball to a ball retains only the information on general ball attributes and behaviour. Similarly, abstracting happiness to an emotional state reduces the amount of information conveyed about the emotional state. Computer scientists use abstraction to understand and solve problems and communicate their solutions with the computer in some particular computer language. d) Function Overloading In order to overload a function, a different signature should be used for each overloaded version. A function signature consists of the list of types of its arguments as well as their order. Here's a set of valid overloaded versions of a function named f: void f(char c, int i); void f(int i, char c); void f(string & s); void f();

void f(int i); void f(char c); Note, however, that a function differing only by return type is illegal (it is legal to use different a return type with a different argument list, though) : int f(); //error; differs from void f(); above only by return type int f(float f); //fine. unique signature Q. 3 Explain the concept of late binding and dynamic binding with the help of at least two examples. Are these concepts related to polymorphism? Explain your answer. (2 marks) Answer 3. Late binding uses CreateObject to create and instance of the application object, which you can then control. For example, to create a new instance of Excel using late binding: Dim oXL As Object Set oXL = CreateObject("Excel.Application") On the other hand, to manipulate an existing instance of Excel (if Excel is already open) you would use GetObject (regardless whether you're using early or late binding): Dim oXL As Object Set oXL = GetObject(, "Excel.Application") To use early binding, you first need to set a reference in your project to the application you want to manipulate. In the VB Editor of any Office application, or in VB itself, you do this by selecting Tools + References, and selecting the application you want from the list (e.g. “Microsoft Excel 8.0 Object Library”). To create a new instance of Excel using early binding: Dim oXL As Excel.Application Set oXL = New Excel.Application In either case, incidentally, you can first try to get an existing instance of Excel, and if that returns an error, you can create a new instance in your error handler. Advantages of Early Binding 1. Your code will run considerably faster, because it can all be compiled up front. With late binding, the code relating to an application you declared as an object has to, in effect, be compiled as it runs. 2. Because your code can all be compiled up front, debugging is far easier – select Debug + Compile, and the compiler will be able to spot syntax errors which would have been missed had you used late binding. 3. You have full access in your project to intellisense (type a keyword and a dot to get a popup list of properties and methods supported by

that keyword, select one to insert it; type a keyword and press F1 to launch the Help topic on that keyword). 4. You have full access to the application's object model via the Object Browser and VBA Help. 5. You have access to the application's built-in constants. For instance, if you are automating Word from Excel, you can use: Dim objWord As Word.Application Set objWord = New Word.Application With objWord .Visible = True .Activate .WindowState = wdWindowStateMaximize .Documents.Open ("c:\temp\temp.doc") End With Furthermore, when you type .WindowState = you'll get a pop-up list of the supported constants, and can simply pick “wdWindowStateMaximize” from the list. If you used late binding, you would need to use: .WindowState = 1 .. and you would need to know (by looking it up in Word's Object Browser) that the value of the constant “wdWindowStateMaximize” happens to be 1. All this makes programming using early binding immeasurably easier than using late binding. Advantages of Late Binding 1. The main advantage is that code which uses late binding is more certain to be versionindependent If you set a reference in a Word 97 project to “Microsoft Excel 8.0 Object Library”, then the project will run OK on a machine which has Office 2000 installed. Word 2000 changes the reference on the fly to the “Microsoft Excel 9.0 Object Library”. But as they famously say, YMMV. Problems have been found in certain circumstances. For instance, if you run a Word 97 project containing a reference to the Excel 8.0 object library on a machine with Office 2000 installed, it will run OK, but you may get the occasional “cannot open macro storage” error unless you save the project in Word 2000. If you do save it in Word 2000, the reference will change to the Excel 9.0 object library. So if you use early binding and support a mixed environment, it may be safest to create separate Word 97 and Word 2000 versions of your addins, despite the maintenance overhead.

2. The more references your project contains, the larger the file size and the longer it takes to compile. 3. Some programming environments don't allow you to create references to another application. Early binding and late binding are related to polymorphism. PolyMorphism Definition: polymorphism describes multiple possible states for a  single property What this means is that different instances (childs) of one thing (object) can behave differently while doing the same action (method). Basically, the commonly used method of explaining this is using the animal analogy. Both Dogs, and Cats are animals, all animals can speak,but when told to speak, they do it differently, a dog may bark, and a cat may meow. Even more simplified, Polymorphism is just overriding methods from a subclass. We will explore one the common way of implementation of the late binding, i.e., of the determination of the actual type of the instance for which the method is called. This is based on the so called virtual method tables. The virtual method table (VMT) is the hidden class data member that is part of any polymorphic class. Any polymorphic class contains exactly one VMT. (The hidden class member is a class member the programmer does not declare the compiler adds it automatically.) The VMT is an array containing pointers to all the virtual methods of the class. Any derived class has its own VMT that contains pointers to all the virtual methods (even those that are not overridden in this class). The pointers to the virtual methods in the VMT of the derived class are in the same order as the pointers to corresponding methods in the base class. Any instance of the polymorphic class contains another hidden data member - the pointer to the VMT. This data member is stored in all the instances at the same place - e.g. at the beginning. The method call is performed in the following way: 1. The program takes the instance, for which the method is called. 2. In the instance, it finds the pointer to the VMT. 3. In the VMT, it finds the pointer to the method called. In all the VMTs this pointer is in the same entry; e.g., the pointer to the Interact() method might be in the VMT of the Particle class and in the VMTs of all the classes derived from the Particle in the first entry. 4. The program uses this pointer to call the method of the actual class of the

instance. Figure illustrates this process for the Particle base class and two derived classes. The values stored in the VMT are set usually at the start of the program or when the class is loaded to the memory. The values of the pointer to the VMT in the instances are set automatically by the constructor. Q. 4 What is the need of UML? Explain the use of any two diagrams used in UML with the help of an example of each. (2 marks) Answer 4.. Unified Modeling Language (UML) is a standardized generalpurpose modeling language in the field of software engineering. UML includes a set of graphical notation techniques to create abstract models of specific systems. The Unified Modeling Language (UML) is the industry-standard language for specifying, visualizing, constructing, and documenting the artifacts of software. UML combines the best practice from data modeling concepts such as entity relationship diagrams, business modeling (work flow), object modeling and component modeling. It can be used with all processes, throughout the software development life cycle, and across different implementation technologies. Sequence Diagram A sequence diagram in Unified Modelling Language (UML) is a kind of interaction diagram that shows how processes operate with one another and in what order. It is a construct of a Message Sequence Chart. Sequence diagrams are sometimes called Event-trace diagrams, event scenarios, and timing diagrams A sequence diagram shows, as parallel vertical lines ("lifelines"), different processes or objects that live simultaneously, and, as horizontal arrows, the messages exchanged between them, in the order in which they occur. This allows the specification of simple runtime scenarios in a graphical manner. For instance, the UML 1.x diagram on the right describes the sequences of messages of a (simple) Restaurant System. This diagram represents a Patron ordering food and wine, drinking wine then eating the food, and finally paying for the food. The dotted lines extending downwards indicate the timeline, time flows from top to bottom. The arrows represent messages (stimuli) from an actor or object to other objects. For example, the Patron sends message 'pay' to the Cashier. Half arrows indicate asynchronous method calls. The UML 2.0 Sequence Diagram supports similar notation to the UML 1.x Sequence Diagram with added support for modeling variations to the standard flow of events.

Simple Restaurant Sequence Diagram

A Sequence diagram is a model that describes how groups of objects collaborate in some behavior over time. The Sequence diagram captures the behavior of a single use case and shows the objects and the messages that are passed between these objects in the timeframe of the specific use case. The Sequence diagram does not show relationships between objects. The Sequence diagram may be used to: Describe the overall sequence of the flow of control when there are many short methods in different classes Show concurrent processes and activations Show time sequences that are not easily depicted in a Collaboration diagram Show general forms that do not deal with objects but with class interaction.

Q. 5 Explain the usage of the following C++ operators with the help of an example program. (a)

size of operator

(b)

Bitwise AND operator

(c)

++ as post increment operator

(d)

Dereferencing operator (2 marks)

Answer 5 b).Bitwise and Operator The bitwise not, or complement, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Digits which were 0 become 1, and vice versa. For example: NOT 0111 (decimal 7) = 1000 (decimal 8)

In many programming languages (including those in the C family), the bitwise NOT

operator is "~" (tilde). This operator must not be confused with the "logical not" operator, "!" (exclamation point), which in C++ treats the entire value as a single Boolean— changing a true value to false, and vice versa, and that C makes a value of 0 to 1 and a value other than 0 to 0. The "logical not" is not a bitwise operation. OR A bitwise takes two bit patterns of equal length, and produces another one of the same length by matching up corresponding bits (the first of each; the second of each; and so on) and performing the logical inclusive OR operation on each pair of corresponding bits. In each pair, the result is 1 if the first bit is 1 OR the second bit is 1 (or both), and otherwise the result is 0. For example: 0101 (decimal 5) OR 0011 (decimal 3) = 0111 (decimal 7)

In the C programming language family, the bitwise OR operator is "|" (pipe). Again, this operator must not be confused with its Boolean "logical or" counterpart, which treats its operands as Boolean values, and is written "||" (two pipes). The bitwise OR may be used in situations where a set of bits are used as flags; the bits in a single binary numeral may each represent a distinct Boolean variable. Applying the bitwise OR operation to the numeral along with a bit pattern containing 1 in some positions will result in a new numeral with those bits set. For example: 0010  (decimal 2) can be considered as a set of four flags. The first, second, and fourth flags are not set (0); the third flag is set (1). The first flag may be set by applying the bitwise OR to this value, along with another value in which only the first flag is set: 0010 (decimal 2) OR 1000 (decimal 8) = 1010 (decimal 10)

This technique is often used to conserve memory in programs dealing with large numbers of Boolean values. XOR A bitwise exclusive or takes two bit patterns of equal length and performs the logical XOR operation on each pair of corresponding bits. The result in each position is 1 if thetwo bits are different, and 0 if they are the same. For example: 0101 XOR 0011 = 0110

In the C programming language family, the bitwise XOR operator is "^" (caret). Assembly language programmers sometimes use the XOR operation as a short-cut to set the value of a register to zero. Performing XOR on a value against itself always yields zero, and on many architectures, this operation

requires fewer CPU clock cycles than the sequence of operations that may be required to load a zero value and save it to the register. The bitwise XOR may also be used to toggle flags in a set of bits. Given the bit pattern, 0010 the first and third bits may be toggled simultaneously by a bitwise XOR with another bit pattern containing 1 in the first and third positions: 0010 XOR 1010 = 1000

Answer 5 c)++ as post increment operator ++expression expression++ The post-increment form of the operator increments x to 2 (x + 1 = 2) and returns the original value of x as the result y:

var x:Number = 1; var y:Number = x++; trace("x:"+x); //traces x:2 trace("y:"+y); //traces y:1 Answer 5 d) Dereferencing operator It is possible to access the value of variables pointed by the pointer variables using pointer. This is performed by using the Dereference operator in C++ which has the notation *. The general syntax of the Dereference operator is as follows: *pointer_variable In this example, pointer variable denotes the variable defined as pointer. The * placed before the pointer_variable denotes the value pointed by the pointer_variable. For example: exforsys = 100; test = exforsys; x = &exforsys; y=*x; In the above example, the assignment takes place as below:

This is

In the above example, the exforsys is a integer variable having the value of 100 stored in memory address location 3501. The variable exforsys is assigned to the variable test in the second statement: test = exforsys; The value of the variable exforsys is 100 and is then copied to the variable test. In the third statement, the address of the variable exforsys denoted by reference operator &exforsys is assigned to the variable x as: x = &exforsys; The address of the variable 3501 and not the contents of the variable exforsys is then copied into the variable x. The fourth statement makes use of the deference operator: y=*x This means that the value pointed to by the pointer variable x gives the value 100 to y. Some points for the programmer to note: The programmer must note that the x refers to the address 3501 whereas *x refers to the value stored in the address 3501 namely 100. . The reference operator is denoted by & and deference operator denoted by * . Both differ in their meaning and functionality. The reference operator denotes the address of. The dereference operator denotes the value pointed by. In short, a deference variable can be denoted as referenced. . If the programmer wants to define more than two pointer variables, then comma operator may be used in this instance. The programmer must carefully place pointer symbol * before each pointer variable. For instance, if the user wishes to define two integer pointer variables, e1 and e2, this can be done as follows: int *e1,*e2; If the programmer declares: int *e1,e2; This means that e1 is a pointer variable pointing to integer data type but e2 is only an integer data type and not a pointer type. The programmer must ensure to place * before each pointer variable.

The dereferencing or indirect addressing is performed using the indirection operator * used to access the value stored in an address. The defining of pointer variable: int* exf; The definition of pointer variable as in the above case is the pointer variable exf. It is also possible to assign value to pointer variable using indirection operator. This gives the same effect as working with variables. For Example: #include void main() { int example,test; int* exforsys; exforsys=&example; example=200; test=200; *exforsys=100; test=*exforsys; cout< cout< }

The output of the above program is 100,100

Q. 6 Write a function swap that exchanges the values of two variables using a third variable, by using the: (a) Pointers (b)& (address of) operator Explain the two functions that you have written. (2 marks) Answer 6. a) void swapArgs(int *parmA,int *parmB) { int temp = *parmA; *parmA = *parmB; *parmB = temp; } Answr 6. b) void swapArgs(int parmA,int parmB) { int temp = parmA; parmA = parmB; parmB = temp; }

Q. 7 Create a class hierarchy for the Worker and Supervisor using C++. The Worker class should include details like worker ID, Name, address of the worker, department ID and Supervisor ID. The classes should have necessary functions to input the required information and a polymorphic function to print the details of the workers or supervisors. For the worker’s this print function should output the worker ID, Name and

Supervisor ID. Whereas for the supervisor’s this function should out put the Name and department ID of the supervisor. Please note that a supervisor is also a worker. Make and state suitable assumptions, if any (4 marks) Answer 7 Class worker { Private : int workerid; Char nsme[15]; Char address[30]; Int department_ID; Public: void input (); Void disp (); }; Class Supervisor : Public Worker { Private : int Supervisor_ID; Public : void input (); Void display (); }

Q. 8 Write a template class “stack” in C++. The class should have  functions for push, pop, stack full and stack empty. Use this  template to create a stack of integer and a stack of character.  Make suitable assumptions, if any. (3 marks) Answer 8.  #include  #include "stack.h" using namespace std ; void main() { typedef Stack FloatStack ; typedef Stack IntStack ; FloatStack fs(5) ; float f = 1.1 ; cout << "Pushing elements onto fs" << endl ; while (fs.push(f)) { cout << f << ' ' ; f += 1.1 ; } cout << endl << "Stack Full." << endl << endl << "Popping elements from fs" << endl ; while (fs.pop(f)) cout << f << ' ' ; cout << endl << "Stack Empty" << endl ; cout << endl ; IntStack is ; int i = 1.1 ; cout << "Pushing elements onto is" << endl ; while (is.push(i)) { cout << i << ' ' ;

i += 1 ; } cout << endl << "Stack Full" << endl << endl << "Popping elements from is" << endl ; while (is.pop(i)) cout << i << ' ' ; cout << endl << "Stack Empty" << endl ; }

Program Output

Pushing elements onto fs 1.1 2.2 3.3 4.4 5.5 Stack Full. Popping elements from fs 5.5 4.4 3.3 2.2 1.1 Stack Empty Pushing elements onto is 1 2 3 4 5 6 7 8 9 10 Stack Full Popping elements from is 10 9 8 7 6 5 4 3 2 1 Stack Empty

Q. 9 Create a class IntStr that stores a positive decimal integer as a string (the maximum number of decimal digits in the string can be assumed to be only 5 digits, so the maximum value that can be stored is 99999, whereas minimum value that can be stored is 00000.). The class should have a copy constructor, and an overloaded + operator. The overloaded + operator should perform the addition. On addition using this + operator, if the length of result exceeds 5 digit then the class should give the result as 00000. Write the necessary main() function to demonstrate the use of the class. (4 marks) Answer 9. class Example { private: int mInteger; public: // constructor with initializer parameter Example( int ParaValue ); // binary arithmetic add operator overloader // adds A and B together and returns a new C Example operator+( const Example& A, const Example& B ); void Display(); }; // constructor Example::Example( int ParaValue ) { mInteger = ParaValue; } // binary arithmetic add operator overloader

Example Example::operator + ( const Example& A, const Example& B); { Example C; C.mInteger = A.mInteger + B.mInteger; return C.mInteger; } Example::Display() { if(mInteger>99999) cout<<”00000”; else cout << mInteger << endl; } int _tmain(int argc, _TCHAR* argv[]) { Example A; Example B; Example C; int a,b; cout<<”enter a,b”; cin>>a>>b; A = Example( a ); B = Example( b ); C = Example( 0 ); C = A + B; C.Display(); return 0; }

Related Documents