Bcs 031
Bcs 031
Bcs 031
com
Last Date of Submission : 15th October, 2019 (For July, 2019 Session)
Question 1
(a) Write advantages of Object Oriented Programming. Also differentiate between Object
Oriented Programming approach and Structured Programming Approach.
Ans:
• As OOP is closer to the real world phenomena, hence, it is easier to map real world
problems onto a solution in OOP.
• The objects in OOP have the state and behaviour that is similar to the real world objects.
• Abstraction techniques are used to hide the unnecessary details and focus is only on the
relevant part of the problem and solution.
• In OOP, the basic units of manipulation are the objects whereas in case of structured
programming, functions are the basic units of manipulation.
Guruignou.com
In OOP, data is hidden within the objects and its manipulation can be strictly controlled
whereas in structure programming the data in the form of variables is exposed to unintended
manipulation too.
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types –
Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Several of the basic types can be modified using one or more of these type modifiers −
signed, unsigned, short, long
(c) Explain the use of followings in C++ programming with an example program for each
(a) if
(b) for
(c) switch
Ans:
(a) if
If statement is used when execution of statement is depend on condition. Syntax of the if
statement
if (condition)
{
statement(s);
}
Example :
Guruignou.com
#include <iostream.h>
int main()
{
int number;
cout<<"Enter a number: ";
cin>>number;
if (number < 0)
{
number = - number;
}
cout<<"The absolute value of number is “ << number;
return 0;
}
Example :
#include<iostream.h>
int main()
{
for (int i = 1; i <= 10; i++)
{
Cout << i <<endl;
}
Guruignou.com
return 0;
}
Question 2 :
(a) What is constructor? Define the class Account with all the basic attributes of a saving bank
account. Define the default constructor, parameterised constructor in Account class. Define
member functions display_balance(),for displaying the balance of account and
cash_withdrawal( ) to withdraw some amount from account. Use appropriate access control
specifiers in this program.
Ans :
A constructor is a member function of a class which initializes objects of a class. In C++,
Constructor is automatically called when object(instance of class) create. It is special member
function of the class.
A constructor is different from normal functions in following ways:
Constructor has same name as the class itself
Constructors don’t have return type
A constructor is automatically called when an object is created.
If we do not specify a constructor, C++ compiler generates a default constructor for us
(expects no parameters and has an empty body).
#include<iostream.h>
class Account
Guruignou.com
{
private:
int balance;
public:
/* Default Constructor */
Account()
{
balance = 0;
}
/* Parameterised Constructor */
Account(int amount)
{
balance = amount;
}
void cash_withdrawal(int amount)
{
balance = balance - amount;
}
void display_balance()
{
cout << "Balance = " << balance << endl;
}
};
void main()
{
Account ob1;
Account ob2(10000);
ob2. cash_withdraw (5000);
ob1.display_balance();
ob2.display_balance();
}
Output
Balance = 0
Balance = 5000
i. Access Specifiers
Access modifiers or Access Specifiers in a class are used to set the accessibility of the class
members. That is, it sets some restrictions on the class members not to get directly accessed by
the outside functions.
public
private
protected
private - The class members declared as private can be accessed only by the functions inside
the class. They are not allowed to be accessed directly by any object or function outside the
class. Only the member functions or the friend functions are allowed to access the private data
members of a class.
protected - Protected access modifier is similar to that of private access modifiers, the
difference is that the class member declared as Protected are inaccessible outside the class but
they can be accessed by any subclass(derived class) of that class.
ii.
Virtual Function
Consider the following simple program as an example of runtime polymorphism. The main thing
to note about the program is that the derived class’s function is called using a base class
pointer. The idea is that virtual functions are called according to the type of the object instance
pointed to or referenced, not according to the type of the pointer or reference.
In other words, virtual functions are resolved late, at runtime.
#include<iostream>
using namespace std;
class Base
{
Guruignou.com
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}
Abstract Class is a class which contains atleast one Pure Virtual function in it. Abstract classes
are used to provide an Interface for its sub classes. Classes inheriting an Abstract Class must
provide definition to the pure virtual function, otherwise they will also become abstract class.
Abstract class cannot be instantiated, but pointers and refrences of Abstract class type
can be created.
Abstract class can have normal functions and variables along with a pure virtual
function.
Classes inheriting an Abstract Class must implement all pure virtual functions, or else
they will become Abstract too.
Example -
#include<iostream.h>
class Base
{
public:
virtual void show() = 0;
};
Guruignou.com
void main()
{
Base *ob1;
Derived ob2;
ob1=&ob2;
ob1->show();
}
Q3.
(a) What is inheritance? Explain different types of inheritance supported by C++ with the help
of example programs.
Inheritance in C++ is a mechanism in which one object acquires all the properties and behaviors
of a parent object.
The idea behind inheritance in C++ is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
Subclass is a class which inherits the other class. It is also called a derived class, extended class,
or child class.
Superclass is the class from where a subclass inherits the features. It is also called a base class
or a parent class.
Single Inheritance - A derived class with only one base class is called single inheritance.
Guruignou.com
Multilevel Inheritance - A derived class with one base class and that base class is a
derived class of another is called multilevel inheritance.
Multiple Inheritance - A derived class with multiple base class is called multiple
inheritance.
Guruignou.com
Heirarchical Inheritance - Multiple derived classes with same base class is called
hierarchical inheritance.
Multipath Inheritance - A derived class with two base classes and these two base
classes have one common base class is called multipath inheritance.
Guruignou.com
#include<iostream.h>
class A
{
public:
A() { cout << "A's constructor called" << endl; }
};
class B : public A
{
public:
B() { cout << "B's constructor called" << endl; }
};
class C : public B
{
public:
C() { cout << "C's constructor called" << endl; }
};
void main()
{
C ob1;
}
Output
(b) Write a C++ program to overload ‘+’ operator to find the sum of length of two given strings.
(Note: if S1 and S2 are two strings then S1+S2 should give the sum of lengths of S1 and S2).
#include<iostream>
using namespace std;
#include<string.h>
class String
{
char str[80];
public :
String(char s[])
{
strcpy(str,s);
}
void operator+(String s)
{
cout << "Total Length :"<< strlen(str)+strlen(s.str);
}
};
int main()
{
String s1("IGNOU");
String s2("University");
s1+s2;
return 0;
}
Q4.
(a) What is stream manipulator? Explain use of setw( ) and setprecision( ) as stream
manipulator. (4)
Guruignou.com
STREAM MANIPULATORS
Many of the stream manipulators are just alternate ways of doing tasks
performed by member functions. A nice benefit is that cascading can be used,
intermixing manipulators and other output statements that use the insertion operator
cout << setw(10) << "Hello" << endl;
setprecision() is a parameterized stream manipulator that performs the same
task as the member function precision()
cout.precision(2); // sets decimal precision to 2 significant digits
cout << setprecision(2); // does the same thing!
setw() is a parameterized stream manipulator that performs the same task as
the member function width()
cout.width(10); // sets field width to 10 for next output
cout << setw(10); // does the same thing!
(b) Write a C++ program to read the contents of a file and display it on console. (5)
#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ifstream fin;
fin.open("out.txt");
Guruignou.com
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
fin.close();
return 0;
}
(c) What is an exception? Explain advantages of exceptions handling .Write a program in C++ to
perform simple arithmetic operations with proper exceptions handling.
An exception is a problem that arises during the execution of a program. A C++ exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.
catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The catch keyword indicates the
catching of an exception.
try − A try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more catch blocks.
#include <iostream>
using namespace std;
try {
z = division(x, y);
cout << z << endl;
} catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Q5.
(a) What is template? Write appropriate statements to create a template class for Stack
data structure in C++.
Templates are powerful features of C++ which allows you to write generic programs. In simple
terms, you can create a single function or a class to work with different data types using
templates.
Templates are often used in larger codebase for the purpose of code reusability and flexibility
of the programs.
Function Templates
Class Templates
FUNCTION TEMPLATES
A function template works in a similar to a normal function, with one key difference.
Guruignou.com
A single function template can work with different data types at once but, a single normal
function can only work with one set of data types.
Normally, if you need to perform identical operations on two or more types of data, you use
function overloading to create two functions with the required function declaration.
However, a better approach would be to use function templates because you can perform the
same task writing less and maintainable code.
A function template starts with the keyword template followed by template parameter/s
inside < > which is followed by function declaration.
In the above code, T is a template argument that accepts different data types (int, float),
and class is a keyword.
CLASS TEMPLATES
Like function templates, you can also create class templates for generic class operations.
Sometimes, you need a class implementation that is same for all classes, only the data types
used are different.
Normally, you would need to create a different class for each data type OR create different
member variables and functions within a single class.
This will unnecessarily bloat your code base and will be hard to maintain, as a change is one
class/function should be performed on all classes/functions.
However, class templates make it easy to reuse the same code for all data types.
class className
Guruignou.com
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};
In the above declaration, T is the template argument which is a placeholder for the data type
used.
Inside the class body, a member variable var and a member function someOperation() are both
of type T.
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
template<class T>
class Stack
{
T s[10];
int top,n;
public:
Stack()
{
top=-1;
cout<<"\n\tEnter the Stack Size : ";
cin>>n;
}
void push(T elt)
{
if(top<n-1)
s[++top]=elt;
else
Guruignou.com
cout<<"\n\tstack is full.Can't insert "<<elt<<endl;
}
void pop()
{
if(top<0)
cout<<"\n\tstack is empty.\n";
else
cout<<"\n\tPoped elt : "<<s[top--];
}
void stk_operation();
};
template<class T>
void Stack<T> :: stk_operation()
{
int choice=1,i;
T elt;
while(choice>0 && choice<3)
{
cout<<"\n\n\t1.PUSH\t2.POP\tAny Key To Exit\n\tChoice : ";
cin>>choice;
switch(choice)
{
case 1 : //push
cout<<"\n\tEnter the Elt to push : ";
cin>>elt;
push(elt);
cout<<"\n\t\tstack content :\n\n\t";
for(i=0;i<=top;i++)
cout<<s[i]<<"\t";
break;
case 2 : //pop
pop();
cout<<"\n\t\tstack content :\n\n\t";
for(i=0;i<=top;i++)
cout<<s[i]<<"\t";
break;
}
}
Guruignou.com
}
void main()
{
clrscr();
cout<<"\n\t\tSTACK OPERATION USING TEMPLATE\n\n";
cout<<"\n\t INT\n";
Stack<int> stk1;
cout<<"\n\t FLOAT\n";
Stack<float> stk2;
int ch;
while(1)
{
cout<<"\n\t\t\tSTACK OPERATION \n\n";
cout<<"\t1.INT STACK\t2.FLOAT STK\tAny Key To Exit\n\tChoice : ";
cin>>ch;
switch(ch)
{
case 1 : //perform stk operation on int stk
stk1.stk_operation();
break;
case 2 : //float
stk2.stk_operation();
break;
default : exit(0);
}
}
}
Polymorphism represents the ability of an object to assume different forms. And it enables the
programmers to create/write programs that are easier to understand and reuse.
Polymorphism provides flexibility to the programmer to write programs that uses single
method for different operations depending on the requirement.
Guruignou.com
In C++ we can define a single abstract class to represent multiple concrete classes. So by
accepting the abstract class type a method can behave differently for different inputs.
TYPES OF POLYMORPHISM
COMPILE-TIME POLYMORPHISM:
The type of polymorphism that is implemented when the compiler compiles a program is called
compile-time polymorphism. C++ supports compile-time polymorphism through method
overloading. This type of polymorphism is also called as static polymorphism or early binding.
RUN-TIME POLYMORPHISM:
The type of polymorphism that is implemented dynamically when a program being executed is
called run-time polymorphism. C++ supports run-time polymorphism by dynamically
dispatching methods at run time through method overriding.
For this type of polymorphism, method invocations are resolved at run time and not at the
compile time.
(6) (c) Write C++ program to demonstrate implementation of friend function. Also explain
advantages of friend function.
Guruignou.com
FRIEND FUNCTION IN C++
If a function is defined as a friend function then, the private and protected data of a class can
be accessed using the function.
The complier knows a given function is a friend function by the use of the keyword friend.
For accessing the data, the declaration of a friend function should be made inside the body of
the class (can be anywhere inside class either in private or public section) starting with
keyword friend.
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
Now, you can define the friend function as a normal function to access the data of the class.
No friend keyword is used in the definition.
class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}
return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be accessed from
// this function because it is a friend function of className.
... .. ...
}
Guruignou.com
EXAMPLE : WORKING OF FRIEND FUNCTION
1. /* C++ program to demonstrate the working of friend function.*/
2. #include <iostream>
3. using namespace std;
4.
5. class Distance
6. {
7. private:
8. int meter;
9. public:
10. Distance(): meter(0) { }
11. //friend function
12. friend int addFive(Distance);
13. };
14.
15. // friend function definition
16. int addFive(Distance d)
17. {
18. //accessing private data from non-member function
19. d.meter += 5;
20. return d.meter;
21. }
22.
23. int main()
24. {
25. Distance D;
26. cout<<"Distance: "<< addFive(D);
27. return 0;
28. }
Output
Distance: 5
Here, friend function addFive() is declared inside Distance class. So, the private data metercan
be accessed from this function.
Disclaimer/Note:
Guruignou.com
These are just the sample of the answers/solutions to some of the questions
given in the Assignments. These sample answers are submitted by students /
private tutors. These sample answers may be seen as the Guide/Help for the
reference to prepare the answers of the questions given the assignment. Student
should read and refer the official study material provided by the university.
https://guruignou.com/