You are on page 1of 20

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

Assignment Set 1

1. Explain Object and class in OOP language.. And explain the key features of OOP. Ans: Objects Objects are the basic run-time entities in an object-oriented system. Programming problem is analyzed in terms of objects and nature of communication between them. When a program is executed, objects interact with each other by sending messages. Different objects can also interact with each other without knowing the details of their data or code. According to Pressman, Objects can be any one of the following: a) External entities b) Things c) Occurrences or events d) Roles e) Organisational units f) Places g) Data Structures Classes A class is a collection of objects of similar type. Once a class is defined, any number of objects can be created which belong to that class. For example, Employee may be a class and Pawan, Sujay and Ganesh are objects of the class employees. Key features of OOP:

Data Abstraction and Encapsulation


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. Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the outside world and only those functions which are stored in the class can access it.

Inheritance Inheritance allows one data type to acquire properties of other data types. Inheritance from a
base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.

Multiple inheritance is a C++ feature not found in most other languages. Multiple inheritance
allows a class to be derived from more than one base class; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as Java or C#, accomplish something similar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data). An interface as in Java and C# can be defined in C++ as a class containing only pure virtual functions, often known as an abstract base class or "ABC". The member functions of such an abstract base classes are normally explicitly defined in the derived class, not inherited implicitly.

Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance. 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. 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 check multiple condition. Syntax: if(condtion1) { if(condtion2) { statement1; statement2; } else if(condtion3) { statement3; } }

Example: Fine large number. //Large.cpp #include<iostream.h> void main() { int a,b,c; cout<<Please enter three numbers.; cin>>a>>b>>c; if((a>b) && (b>c)) count<<a<<is the largest number; else if((b>a) && (b>c)) count<<b<<is the largest number; else if((c>a) && (c>b)) count<<c<<is the largest number; }

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 is a powerful feature of C++ and is known as function overloading. Every overloaded function should however have a different prototype. The following 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 printline(); { for(int i=0;i<25;i++) cout<<-; cout<<endl; } void printline(char ch); {for (int i=0;i<25;i++) cout<<ch; cout<<endl; } void printline(char ch, int n);

{ for (int i=0;i<n;i++) cout<<ch; cout<<endl; } In the above program, the function printline has three different prototypes depending on the arguments passed to it. The relevant function is invoked depending on the type and number of arguments passed to it.

4. Explain the scope and visibility of variables in c++ functions.


Ans: Scope and Visibility of variables in Functions 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 instructions for jump to the function, saving data in registers, pushing arguments to stack and removing them, restoring data, instructions for returning 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 has 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:- While any code may appear in the constructor and destructor it is recommended that code relating to initialising data members in the class be implemented in the constructor. A destructor will perform destroy any dynamic memory that was allocated in the constructor or at some other point in the object life, as well as releasing any system resources that might similarly have been assigned to the object during its life. Constructors always have the same name as their class. Destructors take the name of their class preceded by a tilde (~). A class may have more than one constructor.A class may not have two constructors that agree in terms of the number and type of their parameters.Constructor and destructors are usually defined as public members of their class and may never possess a return value. They may however sometimes be protected so that code outside the class heirarchy can not construct objects of that class. Here is a programming example: #include <string.h> #include <iostream.h> class MyClass { private: int myInt;

char myText[20]; public: MyClass() { myInt = 0; myText[0]='\0'; } MyClass(const MyClass &anObjectOfMyClass) { myInt = anObjectOfMyClass.myInt; myText = anObjectOfMyClass.myText; } MyClass(const int thisint, const char* thattext = 0) :myInt(thisint) { strcpy(myText,thattext); } ~MyClass() { } friend ostream& operator <<(ostream&, MyClass &); }; ostream& operator <<(ostream & os,MyClass &anObjectOfMyClass) { os << anObjectOfMyClass.myInt << "+ " << anObjectOfMyClass.myText << "+"; return os; } void main(void) { MyClass mcObj1; MyClass mcObj2(1,"abcde"); MyClass mcObj3(mcObj2); MyClass mcObj4 = mcObj3; cout << "mcObj1 : " << mcObj1 << endl; cout << "mcObj2 : " << mcObj2 << endl; cout << "mcObj3 : " << mcObj3 << endl; cout << "mcObj4 : " << mcObj4 << endl; return; }

6. Write a program to demonstrate do while statement in c++.


Ans: The do while loop is same as while loop except that the condition is checked after the execution of statements in the do..while loop. Hence in do..while loop, statements inside the loop are executed atleast once. However, in while loop, since the condition is checked before, the statements inside the loop will not be executed if the loop condition is false.

The average.cpp program is rewritten using do..while loop as follows

// average.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 datatypes or classes. It provides a flexible way to work with classes and can make program code look obvious. This is possible only if we inform compiler about how + operator works with distance class. This is exactly what operator overloading feature in C++ does. It helps to use the default operators with the user defined objects for making the code simpler. However there are several problems with operator overloading which you should be aware of. When using operator overloading, the operator should perform only the most obvious function. Otherwise it will lead to more confusion. If you are overloading + operator for distance class it

should add two distance objects, and should not do something else. However some syntactical characteristics of operators cannot be changed even if you want to. For example, you cannot overload a binary operator to be a unary operator and vice versa. Several operators such as dot operator, scope resolution (::) operator, conditional operator (?:) etc cannot be overloaded.Therefore operator overloading should be used for a class where it is required to perform obvious functions with the default operators and there can be no other meaning for the same. Unary operators are those operators which work on one operator. Some of the unary operators are ++, , and minus (-).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. The bellow mentioned example is overloading the increment operator for a class. //unary.cpp # include <iostream.h> class counter { unsigned int count; public: counter() {count=0;} counter(int c) {count=c;} int getcount() {return count;} counter operator ++() { count++; return counter(count);} }; void main()

{ counter c1,c2; c1++; c2=++c1; cout<<c1.getcount()<<endl; cout<<c2.getcount(); }

8. Write a program to illustrate the implementation of inheritance with example your own. Ans: Inheritance is a very powerful feature of object oriented programming. It allows reuse of code without modifying the original code. It also allows flexibility to programmer to make modifications to the program without altering the original code which saves debugging and programming time and effort. Inheritance feature has enabled to distribute class libraries which allows the programmer to use the standard code developed by some another company. 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.

The following 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() { empno=0; strcpy(ename,"); } employee(int n, char ch[25]) { empno=n; strcpy(ename,ch); } void display() {cout<<Emp Code:<<empno; cout<<Name:<<ename; } }; class manager: public employee { protected: float basic; float hra; public: manager():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<<Basic<<basic<<endl; cout<<HRA<<hra<<endl; } }; void main() { clrscr(); employee e1(106,amit); manager m1(205,pawan,40000.00,5000.00); e1.display(); m1.display(); getch(); } In the above program, we have defined a class employee with data members empcode and ename. These have been declared as protected to enable them to be inherited by the derived classes.

Fall 2011 Bachelor of Computer Application (BCA) Semester 2 BC0037 Object Oriented Programming Using C++
Assignment Set 2
1. Explain about polymorphism. Explain its significance. Ans: Polymorphism means the ability to take more than one form. An operation may exhibit different behaviors in different instances. The behavior depends on the data types used in the operation. Polymorphism is extensively used in implementing Inheritance. 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. Operator overloading is a kind of polymorphism. In C++, polymorphism enables the same program code calling different functions of different classesHer we are using 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. 2. What is an inheritance? Explain different types of inheritance.

Ans: Inheritance allows one data type to acquire properties of other data types. Inheritance from a base class may be declared as public, protected, or private. This access specifier determines whether unrelated and derived classes can access the inherited public and protected members of the base class. Only public inheritance corresponds to what is usually meant by "inheritance". The other two forms are much less frequently used. If the access specifier is omitted, a "class" inherits privately, while a "struct" inherits publicly. Base classes may be declared as virtual; this is called virtual inheritance. Virtual inheritance ensures that only one instance of a base class exists in the inheritance graph, avoiding some of the ambiguity problems of multiple inheritance.

Multiple inheritance is a C++ feature not found in most other languages. Multiple inheritance
allows a class to be derived from more than one base class; this allows for more elaborate inheritance relationships. For example, a "Flying Cat" class can inherit from both "Cat" and "Flying Mammal". Some other languages, such as Java or C#, accomplish something similar (although more limited) by allowing inheritance of multiple interfaces while restricting the number of base classes to one (interfaces, unlike classes, provide only declarations of member functions, no implementation or member data). An interface as in Java and C# can be defined in C++ as a class containing only pure virtual functions, often known as an abstract base class or "ABC". The member functions of such an abstract base classes are normally explicitly defined in the derived class, not inherited implicitly. Types of Inheritance:- inheritance is of 5 types 1.Single inheritance: only one baseclass,and one derived class access memberfunctions,datamembers from it. and derived class can't behave again base class. 2.Multilevel inheritance: eg: base class l derived1 class l derived2 class l derived3 class again derived class acts as another base class 3.Multiple inheritance: there are two base classes and one derived class which is derived from both two base classes. base1 class base2class derived class 4.Hirarchical inheritance: in this one common base class and derived class and from those another derived classes. 5.Hybrid inheritance: it is a combination of any above inheritance types, that is either multiple-multilevel multiple-hirarchical, or any other combination. 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. In the second statement, d4=d3+2, d3 invokes the + operator and 2 is passed as an argument. The one argument constructor is invoked to convert 2 (integer datatype) into distance object. However the above implementation has a limitation. The compiler will not understand how to handle statements like d2=10+d1 where the left operand which calls the operand is not a distance object. This can be however handled through a concept known as friend functions. By declaring the operator + as a friend you can accomplish it to handle multiple datatypes. Friend functions are external functions that can access the private data members of a class. However, the class definition should declare the function as a friend. They can act as a bridge between two classes or in other words they can be used when a single function has to operate on multiple datatypes. A function is made friend by just prefixing the keyword friend in the function declaration within the class definition.

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. In the following program we have made the base class function show() as virtual function by prefixing with the keyword virtual. //virtual.cpp

# include <iostream.h> class base { public: virtual void show() // virtual function {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(); } By declaring the base class function as virtual, we now get the output as:

derv1 derv2 In the above program, depending on the contents in the pointer, the compiler decides which class function to call during runtime. This is known as late binding or dynamic binding. Virtual functions are for just name sake and will not be executed many a times. If the virtual function has no specific role in the base but just declared for enabling the derived class objects access through pointers, the function can be declared as a pure virtual function. A pure virtual function is one which does not have any body. There are nine ways that you can declare a virtual function: it can be plain, pure or pure-with-abody. Each of these three can be declared public, private or protected.Well, it's one of those lesser-known facts of the language that a pure virtual function can have a definition (or body). After all, the pure specifier (the "= 0" bit) only says that this class cannot be instantiated - it does not say "this function cannot be implemented here". One of the simplest ways of making a class abstract (cannot be instantiated) is to declare the destructor pure - but destructors simply have to have a body. So, let's look at the various declarations and see what the programmer who uses each is saying. The first thing to point out is that, since the virtual mechanism works down inheritance hierarchies, there is not usually much difference in meaning between a public function and a protected one - it's just a matter of outside visibility rather than "meaning" in the sense.

7. Explain different access specifiers in a class.

Ans: Access specifiers control access to class members. Some access specifiers may also control how classes inherit such constraints. Their primary purpose is to separate the interface of a class from its implementation. A common set of access specifiers that C++ support is:

private (or class-private) restricts the access to the class itself. Only methods that are part of the same class can access private members. protected (or class-protected) allows the class itself and all its subclasses to access the member. The protected access specifier restricts access to member functions of the same class, or those of derived classes. public means that any code can access the member by its name.

8. Write a program in c++ to read a 3X2 matrix and find smallest number in that matrix. Ans:

// matrix.cpp #include<iostream> 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