You are on page 1of 16

Fall 2011 Bachelor of Computer Application (BCA) Semester 2 BC0037 Object Oriented Programming Using C++ 4 Credits

(Book ID: B0681) Assignment Set 1 (40 Marks)

Answer all questions: 1. Explain Object and class in OOP language.. And explain the key features of OOP. Ans: An Object is a program representation of some real-world thing (i.e. person, place or an event).Objects can have both attribute (data) and behaviors (functions or methods). Attributes describe the object with respect to certain parameter and Behavior or functions describe the functionality of the object. Objects with the same data structure and behavior are grouped together as class. I n other words, objects are instanced of a class. Classes are templates that provide definition to the objects of similar type. Objects are like variables created whenever necessary in the program. Classes and Objects support data encapsulation and data hiding which are key terms describing object oriented programming languages. Data and functions are said to encapsulated in an single entity as objects. The data is said to be hidden thus not allowing accidental modification. Inheritance Inheritance is one of the most powerful features of Objects 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 features for any programming language

Polymorphism and Overloading Operator overloading feature allows users to define how basic operators work with objects. The operator + will be adding two numbers when integer variables. However when used with defined strings class,+ operators may concatenate two strings. Similarly same functions with same function. This features of C++ where same operating on is called as polymorphism (Same thing different Forms).Operator overloading is a kind of polymorphism

2. Write a suitable program to show the example of nested if statement. Ans: If statement can be nested in another if statement to multiple conditions. If (condition 1) {if (condition 2) {statement1; Statement2; } else if (condition3) {statement3; } } else staement4;

3. What is function overloading? Write a c++ program to implement a function overloaded. Ans: More than one user defined functions can have same name and perform different operations. This powerful feature of C++ is known as function overloading. Every overloaded function should however have a different prototype. The program implements a overloaded function. Printline() //fnoverload.cpp # include <iostream.h> Void printline(); Void printline(char ch); Void printline(char ch,int,n); Void main() { Printline(); Printline(*) Printline(*20); } Void printli9ne(); {for(int i=0;i<25;i++) Cont<<_; Cout<<endl; }void printline(char ch); {for (int i=0;i>25;i++) Cout<<ch; Cout<<endl; } Void printline(char ch, int n); {for Lint i=o;i<n;i++) Cout<<ch; Cout<<endl: } 4. Explain the scope and visibility of variables in c++ functions. Ans: Functions save memory as all the calls to the function cause the same code to be executed. However, with this there is overhead of execution time as there must be instruction for jump to the function, saving data in registers, pushing arguments to stack and removing them, restring data, instructions for to the calling program and return values. To save execution time of functions, one of the feature in c++ is inline functions. An inline functions code is put with the code in the calling program for every function call. The inline function is written like any other function except that the function declaration begins with the keyword inline. This type of function is suitable for small functions which have to be repeatedly called. This enables the user to write programs using functions which would make programs look neat and less lengthy, at the same time the actual code is inserted in all the places where the function is called after compilation enabling faster execution of the program.

5. Discuss the constructors and Destructors with suitable example. Ans: Constructors and destructors are very important components of a class. Constructors are members functions of a class which same name as the class name. Constructors are called automatically whenever an object of the class is created. This feature makes it very useful to initialize the class data members whenever a new object is created. It also can perform any other function that needs to be performed for all the class without explicitly specifying it. Destructors on the other hand are also member functions with the same name as class but are prefixed with tilde (~) sign differentiate it from the constructor . They are invoked automatically whenever the objects life expires or it destroyed. It can used to return the memory back to life to the operating system if the memory was dynamically allocated. The following program implements the constructor and destructors for a class ?? constdest.cpp # include<iostream.h> class sample { private: Int data: Public Sample() {data=0;COUT<<Constructor invoked<<endl;} ~sample() {cout<<<<Constructor invoked;} Void main() { sample obj1; Obj.display() } The output of above program is Constructor invoked Data=0 Destructor invoked. 6. Write a program to demonstrate do while statement in c++.. Ans: ??average2.cpp # include <iostream.h> void main() {int n=0,a; Int sum=0; cout<<enter five numbers; Do { cin>>a; sum=sum+a;

n++; }while (n<5); Cout<<:average of the numbers is<<(sum?n); } 7. What do you mean by operator overloading? Illustrate with suitable example for overloading Unary operators. Ans: Operator overloading is an interesting feature of C++ that allows programmers to specify how various arithmetic, relational and many other operators work with user defined data types or classes. Unary operators are those operators which work on one operator. Some of the unary operators are + +,--,and minus(-). Operator overloading works similar to any member function of a class. But it is not invoked using dot operator. Just like member function the operator has a return value and takes arguments. It is invoked by the operand which uses it. In case of overloading of unary operators, the calling operand can be either left or right of the operator like in case of increment and decrement operators. While defining the operator functionality for the class the keyword operator is used. Increment operator for class as shown. //unary.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0} Int getcount() {return count;} Void oprerator ++() { count++;} }; Void main() { counter c1; c1++; ++c1; Cout<<c1.getcount(); } In the above example, the operator ++ is defined to return void and take no arguments. All unary operators do not take any arguments as it operates on only one operand and that operand itself invokes the operator. Therefore the operand is sent by default. However the above implementation cannot be used in statements such as c2=c1++; where c1 and c2 are counter variables. This is because the operator ++ returns void which makes an counter variable being assigned void value. 8. Write a program to illustrate the implementation of inheritance with example your own. Ans: The program implements the inheritance. The class manager is inherited from the class employee. //inheritance.cpp # include<iostream.h> # include<string.h>

# include<conio.h> class employee { protected; int empno: char ename[25]; public; employee() {empo=0; strcopy(ename,ch); } void display() {cout<<:EMP Code:<<empno; cout<<Name;<<ename; } }; class manager; pulic employee { protected: float basic; float hra; public: mangaer():employee() { basic=0.0; hra=0.0;} manager(int n,char ch[25],float i, float j): employee(n,ch) { basic=I; hra=j;} void display() { employee::display(); cout<<Baasic<<basic<<endl; cout?<<hRA<<hra<<endl; } }; void main() { clrscr(); employee e1(106,:rahul); manager m1(205,yogesh,40000.00,5000.00); e1 .display(); m1 .display(); getch(); } In r=the above program we hav defined a class employee with data members emcode and ename. These been declared as protected to anable them to be inherited by the derived classes. The employee class also has constructor and a member function display. The class manager has been derived from the class employee through the statement class mangaer: public employee Here public is a keyword which specifies that the class is derived publicly from class employee. We will see other types of inheritance in the next section. The class manager has basic and hra as data members in addition to ename and empcode

In the class manager also,we have defined constructors and a member function display. While initializing the data members of the manager of the manager class, the respective members of the parent class hav to be also initialized. We hav invoked the constructors of the parent class in the following statements maaher(); employee() Manager(int n,char ch[25],float I float j); employee(n.ch).

Fall 2011 Bachelor of Computer Application (BCA) Semester 2 BC0037 Object Oriented Programming Using C++ 4 Credits (Book
ID: B0681) Assignment Set 2 (40 Marks)

1. Explain about polymorphism. Explain its significance. Ans: Virtual functions in C++ are important to implement the concept of polymorphism.
Polymorphism means same content but different forms. In C++, polymorphism enables the same program code calling different functions of different classes. Imagine a situation where you would like to create a class shape and derive classes such as rectangle, circle, triangle etc. Let us suppose each of the classes has a member function draw() that causes the object to be drawn on the screen. You would like to write a common code as following so that you can draw several of these shapes with same code and the shape to be drawn is decided during runtime: Shape *ptrarr[100] for (int j=0;j<n;j++) Ptrarr[j]->draw(); This is an very desirable capability that completely different functions are executed by same function call. If the ptrarr is pointing to a rectangle, a rectangle is drawn. If it is pointint to circle, circle is drawn. This is exactly what is polymorphism. However to implement this approach several conditions should be met. Firstly, all the classes rectangle, circle, triangle should be derived from a single class (Here it is shape class). Secondly, the draw() function must be declared as virtual in the base class (in the shape class). Operator overloading is, a type of polymorphism which allows the same operators to behave differently with different data types/operands.

2. What is an inheritance? Explain different types of inheritance.

Ans: Inheritance is the process of creating new classes known as derived classes from the
existing or base class. The features of the base class are said to be inherited by the derived class. The child class has all the functionality of the parent class and has additional functionalities of its own. Types of Inheritance In the previous section, we discussed single inheritance with one base and derived class. We can have several classes derived from a single base class like shown below. Hierarchial Inheritance
Inheritance can also be multilevel inheritance where another class is derived from the derived class. In such case the grand child class inherits all the properties of child and parent classes.

Multilevel Inheritance The derived class can also have multiple parents which is known as multiple inheritance. Here the child or derived class has two or more parent classes. The child class inherits all the properties of all its parents. Multiple inheritance is implemented same as single inheritance except that both the parent names have to be specified while defining the class. We will discuss multiple inheritance in detail in the next unit.

Multiple Inheritance

In the above example we have created a class employee and a student. Manager class is defined from both of these classes. This is useful in instances when you want to create an employee whose educational qualifications need not be stored such as a worker. We had seen in the inheritance.cpp program, public inheritance. There can also be private inheritance. In the public inheritance, keyword public specifies that objects of derived class can access public member functions of the base class. If the derived class is derived privately then objects of derived class cannot access the public member functions of the base class. Since objects cannot access private or protected members of a class, no members of the base class will be accessible by the objects of the derived class.

Access Specifiers in Private Inheritance The following figure shows accessibility in private inheritance

3. Write a c++ program to implements the relational operator overloading for the distance class. Ans:
The following program implements the program for < relational operator overloading for the distance class. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display(); void getdata(); int operator < (distance d1) { if (feet<d1.feet) return 1; else if (feet==d1.feet) && (inches<d1.inches) return 1; else return 0; } };

void distance :: display() {cout<<feet << <<inches<<endl;} void distance :: getdata() { cout<<Enter distance in feet and inches; cin>>feet >>inches;} void main() { distance d1,d2; d1.getdata(); d2.getdata(); if (d1<d2) cout<<d1.display() << is smaller; else cout<<d2.display()<< is smaller; } In the above program the d1 object invokes the operator < and d2 is passed as an argument. The return value is either 0 or 1 which indicates false or true respectively. Certain compilers support boolean datatype which can be alternatively used instead of integer. The above program also implements display and getdata member functions differently. The member functions are declared inside the class but are defined outside the class. But to specify that the member function belongs to the distance class, the class name is included along with the function name separated by the scope resolution operator (::).

4. Create a class String which stores a string value. Overload ++ operator which converts the characters of the string to uppercase (toupper() library function of ctype.h can be used) Ans:
//string.cpp # include<iostream.h> # include<ctype.h> # include<string.h> # include<conio.h> class string { char str[25]; public: string() { strcpy(str, );} string(char ch[]) { strcpy(str, ch);} void display() { cout<<str;} string operator ++()

{string temp; int i; for(i=0;str[i]!=\0;i++) temp.str[i]=toupper(str[i]); temp.str[i]=\0; return temp; } }; void main() { clrscr(); string s1=hello, s2; s2=s1++; s2.display(); getch(); }

5. Write a note on Overloading of binary operators. Ans: Binary operators are those that work on two operands. Arithmetic operators like + , * etc and
relational operators like <, > etc are some examples of binary operators. Overloading binary operators is different from overloading unary operators mainly in terms of the way it is invoked and arguments passed. When you overload a binary operator, the operand to the left of the operator calls the operator and the operand to the right of the operator is passed as an argument. The following example shows the overloaded + operator for the class distance. # include<iostream.h> class distance { private: int feet, inches; public: distance() {feet=0; inches=0;} distance(int f) {feet=f; inches=0;} distance(int f, int i) {feet=f;inches=i;} void display() {cout<<feet << <<inches<<endl;} distance operator + (distance d1) { int f = feet+d1.feet; int i = inches+d1.inches; return distance(f,i);} }; void main() { distance d1(2,5), d2(1,4),d3, d4;

d3=d1+d2; d3.display(); d4=d3+2; d4.display(); } In the above program, the operator + is overloaded. The declaration shows that a distance object is passed as an argument and an distance object is returned. In the main program, the statement d3=d1+d2 invokes the + operator where d1,d2,d3 are distance objects. The object d1 calls the + operator (left operand) and d2 is passed as an argument (right operand) and after the two objects are added they are returned to the main program which is stored in the d3 object.

6. What is a virtual function? Explain it with an example. Ans: Virtual means existing in effect but not in reality. Virtual functions are primarily used in
inheritance. Let us suppose you have a class base as shown in the following program and two classes derv1 and derv2 are publicly derived from class base. You would like to create a pointer that points to any of the derived class objects. If you create a pointer of derv1, then it can point to derv1 object only. Compiler will complain if you assign any other object is assigned to the pointer. The solution is to create a pointer to Base class. // objectptr.cpp # include <iostream.h> class base { public: void show() {cout<<base<<endl;}}; class derv1:public base { public: void show() {cout<<derv1<<endl;}}; class derv2: public base { public: void show() {cout<<derv2<<endl;}}; void main() { derv1 dv1; derv2 dv2; base *ptr; ptr=&dv1; ptr->show(); ptr=&dv2; ptr->show(); }

The output of the above program will be surprisingly: base base

7. Explain different access specifiers in a class. Ans: The methods are defined as public. These are known as access specifiers. Data and
functions in a class can have any one access specifiers: private, public and protected. Protected access specifier we will discuss later in unit 7 along with inheritance. Private data and functions can be accessed only by the member functions of the class. None of the external functions can access the private data and member functions. Public data and member functions can be accessed through the objects of the class externally from any function. However to access these data and functions, you need to have an object of that class. This feature of object oriented programming is sometimes referred to as data hiding. The data is hidden from accidently getting modified by an unknown function. Only a fixed set of functions can access the data. In a class, the data and functions are private by default so private keyword can be omitted.

Access specifiers in a class

Certain object oriented programming languages refer to methods as messages. Thus d1.display() is a message to d1 to display itself Usually, data are declared as private and functions as public. However, in certain case you may even declare private functions and public data. Please note that the class definition has a semicolon in the end.

Array of objects can also be created. It is similar to array of structures.

8. Write a program in c++ to read a 3X2 matrix and find smallest number in that matrix. Ans: program in c++ to read a 3X2 matrix
include<iostream> using namespace std; int main() { int i,j,sm; int mat[3][2]; cout<<"Enter the values in the matrix:\n"; for(int i=0;i<3;i++) { for(int j=0;j<2;j++) { cin>>mat[i][j]; } } cout<<"Now print the values of the matrix:\n" ; for(int i=0;i<3;i++) { for(int j=0;j<2;j++) { cout<<"The values are :"<<"\t"<<mat[i][j]<<"\n"; } } sm=mat[0][0]; for(int i=0;i<3;i++) { for(int j=0;j<2;j++) { if(sm > mat[i][j]) sm = mat[i][j]; } } cout<<"\n Comparing we get :\n"; cout<<"The smallest number in the matrix is:\t"<<sm; return 0; }

You might also like