You are on page 1of 25

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) Name Riaz Ali Laskar


Answer all questions:

Roll No - 511112806
08 x 05 = 40

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).Object can have both attributes(data) and behaviours (functions and methods). Attributes describe the object with respect to certain paramaters and behaviours or functions describe the functionality of the the object. Objects with the same data structure and behaviour are grouped together as class.In other words , objects are instances of a class . Classes are templets that provide defination to the objects of similar type . Object are like variables created whenever necessary in a program. 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. 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.

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 is the process by which objects can acquire the properties of objects of other class. In OOP, inheritance provides reusability, like, adding additional features to an existing class without modifying it. This is achieved by deriving a new class from the existing one. The new class will have combined features of both the classes. 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.

2. Write a suitable program to show the example of nested if statement.

Ans: //Large.cpp #include <iostream.h> Void main() { Int a,b,c; Cout << please enter three numbers : ; Cin >> a >> b >> c; If((a>b)&&(a>c)) cout << a << is the largest number; else if((b>c)&&(b>a)) cout << b << is the largest number; else if((c>a)&&(c>b)) cout << 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 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; }

4. Explain the scope and visibility of variables in c++ functions. Ans: The several types of variables can be created in C++ which can be different in terms of life, visibility and the way it is initialized. These are also known as storage classes. The three types of storage classes are : Automatic, External and Static variables. Automatic variables is default variable in C++. All the variables we have created and used in programs are automatic variables. These variables can also be declared by prefixing the keyword auto. One of important characteristics of these variables are that they are created only when the function or program block in which they are declared are called. Once the execution of function or module execution is over, the variables are destroyed and the values are lost. The reason for limiting the lifetime of automatic variables is to save memory. When the variables are not be used by the function, they are removed from the memory. They can be accessed only within the function where they are declared. Beyond which they are not idenfiable. By default the automatic variables are not initialized to any specific values unless and until specified. They contain junk value depending on the value stored in the memory. Therefore it is necessary to initialize automatic variables to avoid problems in debugging.

External variables are variables external to any function. Thus they can be accessed by multiple functions. This is the easiest way to share data among various functions. However too many external variables can create problems in debugging as the programmer will have tough time figuring out which function modified which data. Object oriented programming provides an alternative to use external variables. This feature is just to support backward compatibility with C. External variables are also known as global variables and are automatically initialized to zero. These variables are declared before main and declaration statement does not belong to any function. External variables have a life of the file/program in which they are defined. Static variables are a mix of external and automatic variables. They have the scope of the function in which they are defined like automatic variables. But they can retain their values even after the function execution is over and are automatically initialized to zero like external variables. The following program shows the use of the static variables.

5. Discuss the constructors and Destructors with suitable example. Ans: Constructors and destructors are very important components of a class. Constructors are member functions of a class which have 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 objects of 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 to differentiate it from the constructor. They are invoked automatically whenever the objects life expires or it is destroyed. It can be used to return the memory back to the operating system if the memory was dynamically allocated. We will see dynamic allocation of memory in Unit 7 while discussing pointers. 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<<Destructor invoked;} void display() { cout<<Data=<<data<<endl;} }; void main() { sample obj1; obj.display(); } If you run the above program you will get the output as follows: 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 (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of

operators like +, =, or == have different implementations depending on the types of their arguments

//unary.cpp

# include <iostream.h>

class counter

{ unsigned int count;

public:

counter()

{count=0;}

int getcount()

{return count;}

void operator ++()

{ count++;}

};

void main()

{ counter c1;

c1++;

++c1; cout<<c1.getcount(); }

8. Write a program to illustrate the implementation of inheritance with example your own. Ans:

//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();}

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) Name Riaz Ali Laskar


Answer all questions:

Roll No - 511112806
08 x 05 = 40

1. Explain about polymorphism. Explain its significance. Ans: Polymorphism is "acquiring many forms". as it has been stated that c++ has the property of polymorphism.Like as someone said the eg of vehicle...it can be said that the particular operation can acquire one or many forms Its Ablity to take more than one form . It allows single name or operator

to perform different operations depending on datatype passed to it some of the polymorphism used in c++ are operator overloading, function over loading etc.

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

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 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. We can have several classes derived from a single base class like shown below.

Hierarchial Inheritance example 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.

3. Write a c++ program to implements the relational operator overloading for the distance class. Ans: Here relational operater > is used as a + operator

# 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 <<" ft. "<<inches<< " inch " <<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(); }
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

Virtual means existing in effect but not in reality. Virtual functions are primarily used in inheritance. Let us suppose we have a class base as shown in the following program and two classes derv1 and derv2 are publicly derived from class base. we 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.
Ans:

// 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 Even though the address of derived classes is assigned to the pointer, the compiler executes the base class function. However, if the base class function is made virtual, we get the desired result. 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
7. Explain different access specifiers in a class. Ans: Access specifiers are used to identify access rights for the data and

member functions of the class. There are three main types of access specifiers in C++ programming language:

private public protected A private member within a class denotes that only members of the same class have accessibility. The private member is inaccessible from outside the class. Public members are accessible from outside the class. A protected access specifier is a stage between private and public access. If member functions defined in a class are protected, they cannot be accessed from outside the class but can be accessed from the derived class.

When defining access specifiers, the programmer must use the keywords: private, public or protected when needed, followed by a semicolon and then define the data and member functions under it.

8. Write a program in c++ to read a 3X2 matrix and find smallest number in that matrix. Ans: #include <iostream.h>

void main(){ int num[3][2], big = 0 ; cout << "Enter the elements :" ; for(int i=0 ; i< 3 ; i++){ for(int j=0; j<2 ; j++){ cin >> num[i][j] ; } }

for( i=0 ; i< 3 ; i++){ for(int j=0; j<2 ; j++){ if(num[i][j] > big){ big = num[i][j]; } } } cout << " The biggest number is " << big << endl;

cout << "The elements are :" << endl; for( i=0 ; i< 3 ; i++){ for(int j=0; j<2 ; j++){ cout << num[i][j] << " "; } cout << endl; } }

You might also like