Professional Documents
Culture Documents
Last Date of Submission : 15th October, 2019 (For July, 2019 Session)
Question 1
Ans:
• 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.
• OOP is closer to the phenomena in real world due to the use of objects whereas
structured programming is a bit away from the natural way of thinking of human beings.
www.ignousolvedassignment.co.in
• In OOP, the basic units of manipulation are the objects whereas in case of structured
programming, functions are the basic units of manipulation.
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
www.ignousolvedassignment.co.in
if (condition)
{
statement(s);
}
Example :
#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;
}
It is a count controlled loop in the sense that the program knows in advance how many times
the loop is to be executed.
syntax of for loop
for (initialization; decision; increment/decrement)
{
statement(s);
}
The flow diagram indicates that in for loop three operations take place:
Initialization of loop control variable
Testing of loop control variable
Update the loop control variable either by incrementing or decrementing.
www.ignousolvedassignment.co.in
Example :
#include<iostream.h>
int main()
{
for (int i = 1; i <= 10; i++)
{
Cout << i <<endl;
}
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 :
www.ignousolvedassignment.co.in
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
{
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()
www.ignousolvedassignment.co.in
{
Account ob1;
Account ob2(10000);
ob2. cash_withdraw (5000);
ob1.display_balance();
ob2.display_balance();
}
Output
Balance = 0
Balance = 5000
i. Access Specifiers
public
private
protected
public - All the class members declared under public will be available to everyone. The data
members and member functions declared public can be accessed by other classes too. The
public members of a class can be accessed from anywhere in the program using the direct
member access operator (.) with the object of that class.
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
www.ignousolvedassignment.co.in
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
{
public:
virtual void show() { cout<<" In Base \n"; }
};
int main(void)
{
Base *bp = new Derived;
bp->show(); // RUN-TIME POLYMORPHISM
return 0;
}
www.ignousolvedassignment.co.in
iii. Abstract Class
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;
};
void main()
{
Base *ob1;
Derived ob2;
ob1=&ob2;
www.ignousolvedassignment.co.in
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.
Multilevel Inheritance - A derived class with one base class and that base class is a
derived class of another is called multilevel inheritance.
www.ignousolvedassignment.co.in
Multiple Inheritance - A derived class with multiple base class is called multiple
inheritance.
Heirarchical Inheritance - Multiple derived classes with same base class is called
hierarchical inheritance.
www.ignousolvedassignment.co.in
Hybrid Inheritance - Combination of multiple and hierarchical inheritance is called
hybrid inheritance.
Multipath Inheritance - A derived class with two base classes and these two base
classes have one common base class is called multipath inheritance.
www.ignousolvedassignment.co.in
Constructor calling in Multilevel Inheritance -
#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
{
www.ignousolvedassignment.co.in
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)
STREAM MANIPULATORS
www.ignousolvedassignment.co.in
cout << setw(10);// setw() is a parameterized manipulator
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");
char ch;
while(!fin.eof())
{
fin.get(ch);
cout << ch;
}
www.ignousolvedassignment.co.in
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;
int main () {
www.ignousolvedassignment.co.in
int x = 50;
int y = 0;
double z = 0;
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
www.ignousolvedassignment.co.in
FUNCTION TEMPLATES
A function template works in a similar to a normal function, with one key difference.
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.
CLASS TEMPLATES
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.
www.ignousolvedassignment.co.in
However, class templates make it easy to reuse the same code for all data types.
class className
... .. ...
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()
www.ignousolvedassignment.co.in
{
top=-1;
cout<<"\n\tEnter the Stack Size : ";
cin>>n;
}
void push(T elt)
{
if(top<n-1)
s[++top]=elt;
else
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;
www.ignousolvedassignment.co.in
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;
}
}
}
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();
www.ignousolvedassignment.co.in
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.
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.
www.ignousolvedassignment.co.in
In function overloading, two or more methods in a class can use the same name as long as their
parameter declarations are different.
When the compiler encounters a call to an overloaded method, it identifies the correct version
of the overloaded function to be executed by comparing the type and number of arguments.
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.
class class_name
{
... .. ...
www.ignousolvedassignment.co.in
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.
... .. ...
}
www.ignousolvedassignment.co.in
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:
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.
http://www.ignousolvedassignment.co.in
www.ignousolvedassignment.co.in
www.ignousolvedassignment.co.in