You are on page 1of 9

1. Distinguish between procedural language and OOP language. And explain the key features of OOP.

Ans: 1. Procedural language focuses on organizing program statements into procedures or functions. Larger programs were either broken into functions or modules whereas in Object Oriented Programming bundles both data and functions into one unit known as object. 2. One of the main problems with Procedural approach for programming was data being completely forgotten. The emphasis was on the action and the data was only used in the entire process. Whereas in Object Oriented approach overcomes this problem by modeling data and functions together there by allowing only certain functions to access the required data. 3. The procedural languages had limitations of extensibility as there was limited support for creating user defined data types and defining how these data types will be handled whereas in OOP language provides this flexibility through the concept of class. 4. Another limitation of the procedural languages is that the program model is not closer to real world objects For example, if you want to develop a gaming application of car race, what data would you use and what functions you would require is difficult questions to answer in a procedural approach.In the object oriented approach solves this further by conceptualizing the problem as group of objects which have their own specific data and functionality. In the car game example, we would create several objects such as player, car, and traffic signal and so on. Key Features of OOP: Encapsulation: Data and functions are said to be encapsulated in an single entity as object. Data Hiding: The data is said to be hidden thus not allowing accidental modification. Inheritance: Inheritance is one of the most powerful features of Object Oriented Programming Languages that allows you to derive a class from an existing class and inherit all the characteristics and behavior of the parent class. This feature allows easy modification of existing code and also reuses code. The ability to reuse components of a program is an important feature for any programming language. Polymorphism: Polymorphism is the ability of objects belonging to different types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, so this behavior can be implemented at run time (this is called late binding or dynamic binding) Overloading: Operator overloading feature allows users to define how basic operators work with objects. The operator + will be adding two numbers when used with integer variables. However when used with user defined string class, + operator may concatenate two strings. Similarly same functions with same function name can perform different actions depending upon which object calls the function. This feature of C++ where same operators or functions behave differently depending upon what they are operating on is called as polymorphism (Same thing with different forms). Operator overloading is a kind of polymorphism.

2. With a suitable example show that switch () statement differs from the normal if().else statement.

Ans: Solution: If Statement: The if-else statement is used to express decisions. Formally the syntax is
if (expression) statement1 else statement2 where the else part

is optional. The expression is evaluated; if it is true (that is, if expression has a non-zero value), statement1 is executed. If it is false (expression is zero) and if there is an else part, statement2 is executed instead. Since an if tests the numeric value of an expression, certain coding shortcuts are possible. The most obvious is writing
if (expression)

instead of
if (expression != 0)

Sometimes this is natural and clear; at other times it can be cryptic. Because the else part of an if-else is optional,there is an ambiguity when an else if omitted from a nested if sequence. This is resolved by associating the else with the closest previous
else-less if.

For example, in

if (n > 0) if (a > b) z = a; else z = b; the else goes

to the inner if, as we have shown by indentation. If that isn't what you want, braces must be used to force the proper association:
if (n > 0) { if (a > b) z = a; } else z = b;

The ambiguity is especially pernicious in situations like this:


if (n > 0) for (i = 0; i < n; i++) if (s[i] > 0) { printf("..."); return i; } else /* WRONG */ printf("error -- n is negative\n");

The indentation shows unequivocally what you want, but the compiler doesn't get the message, and associates the else with the inner if. This kind of bug can be hard to find; it's a good idea to use braces when there are nested ifs. By the way, notice that there is a semicolon after z = a in

if (a > b) z = a; else z = b;

This is because grammatically, a statement follows the if, and an expression statement like ``z = a;'' is always terminated by a semicolon.
Switch () Statement

The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.
switch (expression) { case const-expr: statements case const-expr: statements default: statements }

Each case is labeled by one or more integer-valued constants or constant expressions. If a case matches the expression value, execution starts at that case. All case expressions must be different. The case labeled default is executed if none of the other cases are satisfied. A default is optional; if it isn't there and if none of the cases match, no action at all takes place. Cases and the default clause can occur in any order. Example:

The break statement causes an immediate exit from the switch. Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape. break and return are the most common ways to leave a switch. A break statement can also be used to force an immediate exit from while, for, and do loops. Falling through cases is a mixed blessing. On the positive side, it allows several cases to be attached to a single action, as with the digits in this example. But it also implies that normally each case must end with a break to prevent falling through to the next. Falling through from one case to another is not robust, being prone to disintegration when the program is modified. With the exception of multiple labels for a single computation, fall-throughs should be used sparingly, and commented.
As a matter of good form, put a break after the last case (the default here) even though it's logically unnecessary.

3. What is function overloading? Write a c++ program to implement a

function overloaded.
Ans: Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks. Example: #include<iostream.h> #include<conio.h> class a { public: int area(int a) { cout<<"enter the side"; cin>>a; return(a*a); } float area(float l,float b) { cout<<"enter the length and breadth": cin>>l>>b; return(l*b); } }; int main()

{ clrscr(); a e; int a; float l,b; cout<<"the area of a square"<<e.area(a); cout<<"the area of a rectangle"<<e.area(l,b); getch(); return 0; } 4. Explain the scope and visibility of variables in c++ functions. Ans: The scope and visibility of variable depends on the scoping identifier, like, auto, external, static and register. When we define a variable, without any of these, they are by default auto. In case of automatic variables, the life of the variable starts when the function is invoked and ends when the function terminated. Its only this particular function for whom the variable is visible. Static variables, when defined inside the funtion, the life starts when the function is invoked first time, and stays until the program ends, this means the variable's life is like a global variable, but it can only be used within the function. Static variable, when defined outside the function, they are very much similar to global variable where any function can access it but only within the file where it has been defined. External variable are global variables, which can be access anywhere in the program, even from with other file. Register variable are local variables, defined inside a function, which is given a register space instead of RAM, but this is dependent on register space availability and it is decided by the OS.

5. Discuss the constructors and Destructors with suitable example.


Ans: Objects generally need to initialize variables or assign dynamic memory during their process of creation to become operative and to avoid returning unexpected values during their execution. For example, what would happen if in the previous example we called the member function area() before having called function set_values()? Probably we would have gotten an undetermined result since the members x and y would have never been assigned a value. In order to avoid that, a class can include a special function called constructor, which is automatically called whenever a new object of this class is created. This constructor function must have the same name as the class, and cannot have any return type; not even void. We are going to implement CRectangle including a constructor: Code: [Select]

// example: class constructor #include <iostream> using namespace std; class CRectangle { int width, height; public: CRectangle (int,int); int area () {return (width*height);} }; CRectangle::CRectangle (int a, int b) { width = a; height = b; } int main () { CRectangle rect (3,4); CRectangle rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; } Quote Output : rect area: 12 rectb area: 30 As you can see, the result of this example is identical to the previous one. But now we have removed the member function set_values(), and have included instead a constructor that performs a similar action: it initializes the values of x and y with the parameters that are passed to it. Notice how these arguments are passed to the constructor at the moment at which the objects of this class are created: Quote CRectangle rect (3,4); CRectangle rectb (5,6); Constructors cannot be called explicitly as if they were regular member functions. They are only executed when a new object of that class is created. You can also see how neither the constructor prototype declaration (within the class) nor the latter constructor definition include a return value; not even void. The destructor fulfills the opposite functionality. It is automatically called when an object is destroyed, either because its scope of existence has finished (for example, if it was defined as a local object within a function and the function ends) or because it is an object dynamically assigned and it is released using

the operator delete. The destructor must have the same name as the class, but preceded with a tilde sign (~) and it must also return no value. The use of destructors is especially suitable when an object assigns dynamic memory during its lifetime and at the moment of being destroyed we want to release the memory that the object was allocated. Code: [Select] // example on constructors and destructors #include <iostream> using namespace std; class CRectangle { int *width, *height; public: CRectangle (int,int); ~CRectangle (); int area () {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) { width = new int; height = new int; *width = a; *height = b; } CRectangle::~CRectangle () { delete width; delete height; } int main () { CRectangle rect (3,4), rectb (5,6); cout << "rect area: " << rect.area() << endl; cout << "rectb area: " << rectb.area() << endl; return 0; }

Quote Output: rect area: 12 rectb area: 30 Logged

6 Write a program in c++ to compute the LCM of two numbers..


Ans: #include <stdio.h> #include <conio.h> void main() { int num1, num2, gcd, lcm, remainder, numerator, denominator; clrscr(); printf("Enter two numbers\n"); scanf("%d %d", &num1,&num2); if (num1 > num2) { numerator = num1; denominator = num2; } else { numerator = num2; denominator = num1; } remainder = num1 % num2; while(remainder !=0) { numerator = denominator; denominator = remainder; remainder = numerator % denominator; } gcd = denominator; lcm = num1 * num2 / gcd; printf("GCD of %d and %d = %d \n", num1,num2,gcd); printf("LCM of %d and %d = %d \n", num1,num2,lcm); }

7. What do you mean by operator overloading? Illustrate with suitable example for overloading Unary operators.

You might also like