[go: up one dir, main page]

0% found this document useful (0 votes)
11 views27 pages

c++ all soln

The document provides a comprehensive overview of Object Oriented Programming (OOP) and its comparison with Procedure Oriented Programming (POP), detailing their advantages and disadvantages. It explains key OOP concepts such as classes, objects, encapsulation, inheritance, polymorphism, and control structures, along with practical examples and code snippets. Additionally, it covers advanced topics like function overloading, pointers to objects, inline functions, and operator overloading.

Uploaded by

Santosh Dahal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

c++ all soln

The document provides a comprehensive overview of Object Oriented Programming (OOP) and its comparison with Procedure Oriented Programming (POP), detailing their advantages and disadvantages. It explains key OOP concepts such as classes, objects, encapsulation, inheritance, polymorphism, and control structures, along with practical examples and code snippets. Additionally, it covers advanced topics like function overloading, pointers to objects, inline functions, and operator overloading.

Uploaded by

Santosh Dahal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

1|Page

Object Oriented Programming Language


Regular/back exam 2070
Stream: Diploma in Computer Engineering(I/II)
1. Differentiate procedure oriented and object oriented programming along with advantages.
 The differentiate between procedure oriented and object oriented programming are listed in the table
below:-
Procedure Oriented Programming Object Oriented Programming
1. In POP programs are divided into smaller 1. In OOP programs are divided into parts
parts called function. called object.
2. Importance is given to function as well as 2. Importance is given to data rather than
sequence of actions to be done. procedure or function.
3. Follows top down approach. 3. Follows bottom up approach.
4. It does not have any access specifiers. 4. It has access specifiers. They are: public,
5. It focuses on process rather than data. private & protected.
6. It takes a sequence of things to be done 5. Through inheritance we can eliminate the
such as reading, calculating and printing. redundant code and extend the use of
7. Example : C , FORTRAN etc existing class.
6. Object oriented System can be easily
upgraded from small to larger system.
7. Example : c++ , java , c# etc
The advantage of OOP and POP is as follows:

2. What are the advantage and disadvantage of OOP and POP .


Advantages of Procedural Programming:
I. Its relative simplicity and ease of implementation of compilers and interpreters.
II. The ability to re-use the same code at different places in the program without copying it.
III. An easier way to keep track of program flow.
IV. The ability to be strongly modular or structured.
V. Needs only less memory.
Disadvantages of Procedural Programming:
I. Data is exposed to whole program, so no security for data.
II. Difficult to relate with real world objects.
III. Difficult to create new data types reduces extensibility.
IV. Importance is given to the operation on data rather than the data.

The advantages of object oriented programming language are as follows :

I. The programs written with OOP are really easy to understand.


II. Since everything is treated as objects, so we can model a real-world concept using OOP.
III. OOP approach offers the reusability of classes. We can reuse the classes that are already created without
writing them again and again.
IV. Since the parallel development of classes is possible in OOP concept, It results in the quick development
of the complete programs.
2|Page

V. Programs written in OOP technique are marginally easier to test, manage as well as maintain.
VI. It is a secured development technique since data is hidden and can’t be accessed by external functions.
Disadvantage Of OOP
I. Designing a program in OOP concept is a little bit tricky.
II. The programmer should have a proper planning before designing a program using OOP approach.
III. Since everything is treated as objects in OOP, the programmers need proper skill such as design skills,
programming skills, thinking in terms of objects etc.
IV. The size of programs developed with OOP is larger than the procedural approach.
V. Since larger in size, that means more instruction to be executed, which results in the slower execution of
programs.

3. Explain the characteristics of OOP.


The characteristics of OOP are listed and explained below:-
I. Object
II. Class
III. Data hiding and encapsulation
IV. Dynamic binding
V. Message passing
VI. Inheritance
VII. Polymorphism
 Object:
Object is the collection of number of entities. Object takes up space in the memory. Object are instances of
classes when a program is executed. The object interacts by sending message to one another. Each object
contains data and code to manipulate the data. Objects can interact with each other without knowing details of
each other data or code.
 Class:
Class is the collection of object of similar types. Objects are variable of type class. Once a class is defined, we
can create any number of objects belonging to their class. Eg:- grapes, oranges, banana are the member of class
fruits.
 Data abstraction and encapsulaton :
Combining data and function into a single unit is called encapsulation. Class contains both data and function.
Data is not accessible from the outside world and only these functions which are present in the class can access
the data. The insulation of the data from direct access by the program is called data hiding.
 Inheritance:
It is the process by which object of one class acquire the property or feature of another class. The concept of
inheritance provide the idea of reusability means we can add additional features to an existing class without
modifying it. This is possible by deriving a new class from the existing class.
 Polymorphism :
3|Page

A Greek term means ability to take more than one form. An operation contains different behaviours in different
instance. The behavior depends upon the type of data used in the operation.Examples of
polymorphism:Operator overloading ,Function overloading etc
 Dynamic binding :
It refers to linking of function call with function definition. When binding takes place at run time it is called
dynamic binding.
 Message passing:
The process by which one object can interact with other object is called message passing.
4. What do you mean by control structures? Illustrate object and class with suitable examples.
 Programs could be written in terms of only three control structures, namely, the sequence structure, the
selection structure and the repetition structure.
a) Sequence Structure
The sequence structure is built into C++. Unless directed otherwise, C++ statements execute one after the other
in the order in which they are written—that is, in sequence.
b) Selection Statements
C++ provides three types of selection statements .The if selection statement either performs (selects) an action if
a condition (predicate) is true or skips the action if the condition is false. The if...else selection statement
performs an action if a condition is true or performs a different action if the condition is false. The switch
selection statement performs one of many different actions, depending on the value of an integer expression.

c) Repetition Statements
C++ provides three types of repetition statements that enable programs to perform statements repeatedly as long
as a condition remains true. The repetition statements are the while, do...while and for statements.

 Class: The building block of C++ that leads to Object Oriented programming is a Class. It is a user
defined data type, which holds its own data members and member functions, which can be accessed and
used by creating an instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but
all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
Eg:
#include <iostream>
using namespace std;
class Student { // class
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
void insert(int i, string n)
{
4|Page

id = i;
name = n;
}
void display()
{
cout<<id<<" "<<name<<endl;
}
};
int main(void) {
Student s1; //creating an object of Student
Student s2; //creating an object of Student
s1.insert(201, "Sonoo");
s2.insert(202, "Nakul");
s1.display();
s2.display();
return 0;
}

When class is defined, only the specification for the object is defined; no memory or storage is allocated.To use
the data and access functions defined in the class, you need to create objects.

5. What is function overloading? Demonstrate with suitable example.


 If any class has multiple functions with same names but different parameters and return type, they are
said to be function overloading. Function overloading allows us to use the same name for different
functions to perform similar or different work in same class.
#include <iostream>
using namespace std;

void print(int i) {
cout << " Here is int " << i << endl;
}
void print(double f) {
cout << " Here is float " << f << endl;
}
void print(char const *c) {
cout << " Here is char* " << c << endl;
}

int main() {
print(10);
print(10.10);
print("ten");
return 0;
}
5|Page

6. Explain pass by reference and return by reference with examples.

 Pass-by-reference means to pass the reference of an argument in the calling function to the
corresponding formal parameter of the called function. The called function can modify the value of the
argument by using its reference passed in. The following example shows how arguments are passed by
reference. The reference parameters are initialized with the actual arguments when the function is called.

#include <iostream.h>
void swapnum(int &i, int &j) // pass by refence
{
int temp = i;
i = j;
j = temp;
}

int main(void) {
int a = 10;
int b = 20;

swapnum(a, b);
cout<<a <<b;
return 0;
}
When the function swapnum() is called, the values of the variables a and b are exchanged because they are
passed by reference. The output is:
A is 20 and B is 10
 Return by reference

A C++ program can be made easier to read and maintain by using references rather than pointers. A C+
+ function can return a reference in a similar way as it returns a pointer. When a function returns a
reference, it returns an implicit pointer to its return value. This way, a function can be used on the left
side of an assignment statement. For example, consider this simple program
#include <iostream>
using namespace std;
int num; // Global variable
int& test(); // Function declaration
int main()
{
test() = 5;
cout << num;
return 0;
}
int& test()// function returning by reference
{
return num;
}
6|Page

Output
5

7. Define inline function? What are advantage and disadvantage of inline function? WAP to
calculate the area of cube and rectangle using inline function.
 C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the
compiler places a copy of the code of that function at each point where the function is called at
compile time.
Two ways to make function Inline are:
i. Using the keyword inline in front of function
inline int A::add(int a, int b)
{
return (a + b);
}

ii. Defining a function inside the class.


Class A
{
Public:
int add(int a, int b);
};

Pros :-
1. It speeds up your program by avoiding function calling overhead.
2. It save overhead of variables push/pop on the stack, when function calling happens.
3. It save overhead of return call from a function.
4. It increases locality of reference by utilizing instruction cache.
5. By marking it as inline, you can put a function definition in a header file (i.e. it can be included in
multiple compilation units, without the linker complaining)

Cons :-
1. It increases the executable size due to code expansion.
2. C++ inlining is resolved at compile time. Which means if you change the code of the inlined function,
you would need to recompile all the code using it to make sure it will be updated
3. When used in a header, it makes your header file larger with information which users don’t care.
4. As mentioned above it increases the executable size, which may cause thrashing in memory. More
number of page fault bringing down your program performance.
5. Sometimes not useful for example in embedded system where large executable size is not preferred at all
due to memory constraints.
7|Page

#include<iostream.h>
#include<conio.h>
class power
{
public:
inline int square(int n)
{
return n*n;
}
inline int cube(int n)
{
return n*n*n;
}
};
void main()
{
int n,r;
power p;
clrscr();
cout<<“\nEnter the Number: \n” ;
cin>>n;
r=p.square(n);
cout<<“\nSquare of “<<n<<” = “<<r<<endl;
r=p.cube(n);
cout<<“\nCube of “<<n<<” = “<<r<<endl;
getch();
}
8. Discuss about pointer to objects with suitable examples.
 A variable that holds an address value is called a pointer variable or simply pointer.
Pointer can point to objects as well as to simple data types and arrays.sometimes we dont know, at the
time that we write the program , how many objects we want to creat. when this is the case we can
usenew to creat objects while the program is running. new returns a pointer to an unnamed objects. lets
see the example of student that wiil clear your idea about this topic.
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
int rollno;
string name;
public:
student():rollno(0),name("")
{}
student(int r, string n): rollno(r),name (n)
8|Page

{}
void get()
{
cout<<"enter roll no";
cin>>rollno;
cout<<"enter name";
cin>>name;
}
void print()
{
cout<<"roll no is "<<rollno;
cout<<"name is "<<name;
}
};
void main ()
{
student *ps=new student;
(*ps).get();
(*ps).print();
delete ps;
}
9.WAP to illustrate objects function argument. The program include three functions gettime( ), puttime( ),
and sumtime( ) in hour and minute format. The sum time( ) function should take object as argument.
10. What is operator overloading? Explain the unary operator overloading with examples.
 In C++, we can make operators to work for user defined classes. This means C++ has the ability to
provide the operators with a special meaning for a data type, this ability is known as operator
overloading.For example, we can overload an operator ‘+’ in a class like String so that we can
concatenate two strings by just using +.Other example classes where arithmetic operators may be
overloaded are Complex Number, Fractional Number, Big Integer, etc
 The unary operator operates on the single operand (data) are called unary operators. The unary operators
in C++ are either used as prefix or postfix with the operand. The unary operators either prefix of postfix
can be overloaded with non static member function taking no argument or a non member function
(usually global function) taking one argument. After overloading the operator, it can be applied to an
object in the same way as it is applied to the base types. The unary operator defined as a non static
member function has the following form:

#include <iostream>
using namespace std;
class temp
{
private:
int count;
public:
9|Page

temp()
{
count=5;
}
void operator++()
{
count=count+1;
}
void display()
{
cout<<"count="<<cout;
}
};
int main()
{
temp t;
++t;
t.display();
return 0;
}

 What are the operators that cannot be overloaded? Write a program to demonstrate the binary
operator. OR Write a program to add two complex number using operator overloading + operator.
 The operator that cannot be overloaded are :
I. “.” Member access or dot operator
II. “? : ” Ternary or conditional operator
III. “::” Scope resolution operator
IV. “.*” Pointer to member operator
V. “sizeof” The object size operator
VI. “typeid” Object type operator

#include<iostream>
using namespace std;

class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
10 | P a g e

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
 What is inheritance? Explain types of inheritance.
Refer class note

 Describe virtual base class. WAP to illustrate virtual function.


 A C++ virtual function is a member function in the base class that you redefine in a derived class. It is
declared using the virtual keyword. It is used to tell the compiler to perform dynamic linkage or late
binding on the function.An ambiguity can arise when several paths exist to a class from the same base
class. This means that a child class could have duplicate sets of members inherited from a single base
class. C++ solves this issue by introducing a virtual base class.
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
11 | P a g e

{
A *a;
B b;
a = &b;
a->display();
return 0;
}
In the above example, * a is the base class pointer. The pointer can only access the base class members
but not the members of the derived class. Although C++ permits the base pointer to point to any object
derived from the base class, it cannot directly access the members of the derived class. Therefore, there
is a need for virtual function which allows the base pointer to access the members of the derived class.
 Explain about I/O stream class hierarchy.
 All the stream classes are derived from the base class ios, which stores the state of the stream and
handles error. The ios class has an associated streambuf object that acts as the buffer for the stream.
The istream and ostream classes, devided from ios, are meant for input and output, respectively. The
iostream class uses multiple inheritance to acquire the capabilities of both istream and ostream class
and there for support both input and out. The classes iostream_withassign, ostream_withassign and
istream_withassign are derived from istream, ostream and iostream, respectively, by adding the
definition of the assignment operator (=) so that we can redirected I/O by assigning one stream to
another. The predefined stream cout, cerr and clog are of class ostream_withassign where as cin is an
instance of istream_withassign class.

 Define Templates or generic programming ? Explain function template and class template.
 The method of Generic Programming is implemented to increase the efficiency of the code. Generic
Programming enables the programmer to write a general algorithm which will work with all data types.
It eliminates the need to create different algorithms if the data type is an integer, string or a character.
Function Templete
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.

Syntax: template <class T>


T someFunction(T arg)
{
... .. ...
12 | P a g e

// Exmple program of Function template


// If two characters are passed to function template, character with larger ASCII value is displayed.
#include <iostream>
using namespace std;
// template function
template <class T>
T Large(T n1, T n2)
{
return (n1 > n2) ? n1 : n2;
}
int main()
{
int i1, i2;
float f1, f2;
char c1, c2;
cout << "Enter two integers:\n";
cin >> i1 >> i2;
cout << Large(i1, i2) <<" is larger." << endl;
cout << "\nEnter two floating-point numbers:\n";
cin >> f1 >> f2;
cout << Large(f1, f2) <<" is larger." << endl;
cout << "\nEnter two characters:\n";
cin >> c1 >> c2;
cout << Large(c1, c2) << " has larger ASCII value.";
return 0;
}

Output

Enter two integers:


5
10
10 is larger.

Enter two floating-point numbers:


12.4
10.2
12.4 is larger.

Enter two characters:


z
Z
z has larger ASCII value.
13 | P a g e

Template Class

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.

template <class T>


class className
{
... .. ...
public:
T var;
T someOperation(T arg);
... .. ...
};

// Program to demonstrate Template class


1. #include <iostream>
2. using namespace std;
3.
4. template <class T>
5. class Calculator
6. {
7. private:
8. T num1, num2;
9.
10. public:
11. Calculator(T n1, T n2)
12. {
13. num1 = n1;
14. num2 = n2;
15. }
16.
17. void displayResult()
18. {
19. cout << "Numbers are: " << num1 << " and " << num2 << "." << endl;
20. cout << "Addition is: " << add() << endl;
21. cout << "Subtraction is: " << subtract() << endl;
22. cout << "Product is: " << multiply() << endl;
23. cout << "Division is: " << divide() << endl;
24. }
25.
26. T add() { return num1 + num2; }
27.
28. T subtract() { return num1 - num2; }
29.
30. T multiply() { return num1 * num2; }
31.
32. T divide() { return num1 / num2; }
33. };
14 | P a g e

34.
35. int main()
36. {
37. Calculator<int> intCalc(2, 1);
38. Calculator<float> floatCalc(2.4, 1.2);
39.
40. cout << "Int results:" << endl;
41. intCalc.displayResult();
42.
43. cout << endl << "Float results:" << endl;
44. floatCalc.displayResult();
45.
46. return 0;
47. }

i) Virtual destructor:
 Deleting a derived class object using a pointer to a base class that has a non-virtual destructor results in
undefined behavior. To correct this situation, the base class should be defined with a virtual destructor.
For example, following program results in undefined behavior. Making base class destructor virtual
guarantees that the object of derived class is destructed properly, i.e., both base class and
derived class destructors are called. For example :
using namespace std;

class base {
public:
base()
{ cout<<"Constructing base \n"; }
virtual ~base()
{ cout<<"Destructing base \n"; }
};

class derived: public base {


public:
derived()
{ cout<<"Constructing derived \n"; }
~derived()
{ cout<<"Destructing derived \n"; }
};

int main(void)
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
 Output:
 Constructing base
 Constructing derived
 Destructing derived
 Destructing base
15 | P a g e

Regular/Black 2073
Attempt any eight questions

1) What is object oriented programming language? Explain its features with examples.

2) What is function overloading? Explain with a simple program.

3) What is object and class? WAP to implement class and object.

4) What is constructor and destructor? Write a simple program using constructor.


 Constructors are special class functions that has the same name as that of the class which is
called the whenever an object is created. Constructors initialize values to object members after
storage is allocated to the object.
 Whereas Destructor is a special class function which destroys the object as soon as the scope
of object ends. The destructor is called automatically by the compiler when the object goes out
of scope.The syntax for destructor is same as that for the constructor, the class name is used
for the name of destructor, with a tilde ~ sign as prefix to it.

#include<iostream.h>
#include<conio.h>
Class A
{
Int I;
Public:
A( );
}
A::A( )
16 | P a g e

{
i=1;
}
Int main( )
{
A a1;
Cout<< a1.i;
Return 0;
}

5) When are constructor and destructor called ? Write a program to demonstrate them .
 Constructor is called when the object of its associated class is created. Destructor is called automatically when
the created object goes out of scope.
class A
{
// constructor
A()
{
cout << "Constructor called";
}

// destructor
~A()
{
cout << "Destructor called";
}
};

int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
17 | P a g e

Constructor called

Constructor called

Destructor called

Destructor called

6) What is friend function and friend class? Expalin with suitable examples.
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.
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.

Friend Class
18 | P a g e

 A friend class can access private and protected members of other class in which it is
declared as friend. It is sometimes useful to allow a particular class to access private
members of other class. For example a LinkedList class may be allowed to access private
members of Node.
class B;
class A
{
// class B is a friend class of class A
friend class B;
}

class B
{
}

9. Explain binary operator overloading. Overload any binary operator with a simple example.
 The operators which operate in two operands (data) are called binary operators. The binary operator
function can be defined by either a non static member function taking one argument or a non member
function (usually global function) taking two arguments. After overloading any operator it can be
applied to an object in the same way as it is applied to the basic type. The binary operator defined as a
non static member function has the following from:
// binary operator overloading to concatenate two string

1. #include<iostream>
2. #include<conio.h>
3. using namespace std;
4.
5. class String
6. {
7. char str[20]; //member variable for string input
8. public:
9. void input() //member function
10. {
11. cout<<"Enter your string: ";
12. cin.getline(str,20);
13. }
14. void display() //member function for output
15. {
16. cout<<"String: "<<str;
17. }
18. String operator+(String s) //overloading
19. {
20. String obj;
21. strcat(str,s.str);
22. strcpy(obj.str,str);
19 | P a g e

23. return obj;


24. }
25. };
26. void main()
27. {
28. String str1,str2,str3; //creating three object
29. str1.input();
30. str2.input();
31. str3=str1+str2;
32. str3.display(); //displaying
33. getch();
34. }

Output

Enter your string : santosh

Enter your string : dahal

String : santoshdahal

1. Define inheritance. Explain the term base class and derive class with a suitable example.
 Inheritance is the process of creating a new class from the existing class. New classes inhert some of the
properties and behavior of the existing class. New classes inhert some of the properties and behavior and
the properties of the existing class. Inheritance allows us to create a opportunity to reuse the code
functionality and fast implementation of time.When creating a class instead of writing completely new
data member and member function, the programmer can design a new class that should inhert the
member of existing class. The existing class is called base class and the new class is referred as derived
class.
Base class : A base class is a class from which other classes are derived in an object-oriented programming
language. It used for creation of other classes that can reuse the code implicitly inherited from the base
class (except constructors and destructors). It is also called as parent class or Superclass.
Properties :

1 ) Base classes are automatically instantiated before derived classes.

2 ) Base class members can be accessed from the derived class.

3 ) The derived class can communicate to the base class during instantiation by calling the base class
constructor.

For example, "vehicle" can be a base class from which "car" and "bus" are derived. Cars and buses are both
vehicles, but each represents its own specialization of the vehicle base class. A base classhas the following
properties: Base classes are automatically instantiated before derived classes.
20 | P a g e

Derived Class :

A derived class is a class derived from another existing class i.e base class.A derived class acquired the
properties of base class.While inheriting from base class, the derived class implicitly inherits all the members
(except constructors and destructors) which it reuses, extends and modifies the behavior of the base class.It Is
also called as Child class .

Consider a base class Shape and its derived class Rectangle as follows −
#include <iostream>
using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;

return 0;
}

Here , shape is base class and Rectangle is a derived class .


21 | P a g e

2. What is virtual function? Write short notes on abstract classes.


A virtual function a member function which is declared within a base class and is re-defined(Overriden)
by a derived class. When you refer to a derived class object using a pointer or a reference to the base
class, you can call a virtual function for that object and execute the derived class’s version of the
function.
// CPP program to illustrate
// concept of Virtual Functions
#include<iostream>
using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print ()
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();
}
Output:
print derived class
show base class
22 | P a g e

 A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t
have implementation, we only declare it. A pure virtual function is declared by assigning 0
in declaration. See the following example.
 A class is abstract if it has at least one pure virtual function.
#include<iostream>
using namespace std;

class Base // abstract class


{
public:
virtual void show() = 0; // pure virtual function
};

class Derived: public Base


{
public:
void show() { cout << "In Derived \n"; }
};

int main(void)
{
Base *bp = new Derived();
bp->show();
return 0;
}
 Output:
 In Derived

3. Explain the function open( ) while opening file. Create a simple file with open( ) function.
 Open( ) is used to open the file other than using a constructor . There are two parameter in opening a file
first is name of the file and another is the mode in which the file is to be open.
Syntax :

open (filename, mode);

// program to create a file using open function


#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile;
// open file employee.txt
myfile.open ("employee.txt");// check file location
if(myfile.is_open())
{
cout<<"File is open"<<endl;
myfile << "Writing into a file.\n";
myfile.close();
}
23 | P a g e

else{
cout<<"Error in file opening"<<endl;
}
return 0;
}

48. Write short notes on:


a) Function templates:
b) Visibility mode in OOP:
 Explain private public and protected

a) Hierarchical inheritance:

Object Oriented Programming Language


2075 R/B
Attempt any eight questions

1) Differentiate between Object Oriented programming and procedure oriented programming with
suitable examples.
 The differentiate between Object Oriented and procedure Oriented programming languages are given in the
table below;
Procedure Oriented Programming Object Oriented Programming

a. In POP programs are divided into smaller a. In OOP programs are divided into parts
parts called function. called object.
b. Importance is given to function as well as b. Importance is given to data rather than
sequence of actions to be done. procedure or function.
c. Follows top down approach. c. Follows bottom up approach.
d. It does not have any access specifiers. d. It has access specifiers. They are: public,
e. It focuses on process rather than data. private & protected.
f. It takes a sequence of things to be done e. Through inheritance we can eliminate the
such as reading, calculating and printing. redundant code and extend the use of
g. Examples: FORTAN, COBOL, Pascal, C existing class.
etc. f. Object oriented System can be easily
upgraded from small to larger system.
g. Example: C++, JAVA, Smalltalketc
24 | P a g e

2) What is function overloading? Explain with suitable examples.

3) What do you mean by data encapsulation? Explain visibility modifier in brief.


 data encapsulation up
 Access modifiers are used to implement an important feature of Object Oriented Programming known as Data
Hiding.There are 3 types of access modifiers available in C++:
I. Public
II. Private
III. 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 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

4) What is friend function? Write a program to add private data member of two classes using friend
functions.
 A friend function of a class is defined outside that class' scope but it has the right to access all private and
protected members of the class. Even though the prototypes forfriend functions appear in the class
definition,friends are not member functions.
#include<iostream>
usingnamespace std;

// forward declaration
class B;
class A {
private:
intnumA;
public:
A():numA(12){}
// friend function declaration
friendintadd(A, B);
};

class B {
private:
int numB;
public:
B( ) : numB(1){}
// friend function declaration
Friend int add(A , B);
25 | P a g e

};

// Function add() is the friend function of classes A and B


// that accesses the member variables numA and numB
intadd(A objectA, B objectB)
{
return(objectA.numA+objectB.numB);
}

intmain()
{
AobjectA;
B objectB;
cout<<"Sum: "<<add(objectA,objectB);
return0;
}

5) Define parameterized constructor and explain it with suitable examples.


 The constructor which has one or many parameters is called parameterized constructor. Sometimes it is
necessary to create objects with different initial values. The default constructor mechanism does not solve
the problem in the case. So we can make constructor that takes arguments and initializes the data member
from the values in the argument list.

Class A
{
A(int a);
};

#include<iostream>
#include<conio.h>

usingnamespacestd;

class Example {
// Variable Declaration
int a, b;
public:

//Constructor
26 | P a g e

Example(int x , int y) {
// Assign Values In Constructor
a = x;
b = y;
cout<<"Im Constructor\n";
}

Void Display() {
cout<<"Values :"<< a <<"\t"<< b;
}
};

Int main() {
Example Object(10, 20);
// Constructor invoked.
Object.Display();

// Wait For Output Screen


getch();
return0;
}

6) WAP to overload binary (+) operator for concatenation of two strings.

7) Explain base and derive class with suitable examples.

8) What do you mean by stream? Explain output and input output streams.
 A stream is a name given to a flow of data at the lowest level. At the lowest level, data is just the binary data
without any notion of data type. Different streams are used to represent the different kinds of data flow such
as whether data is flowing into the memory or out of the memory.The stream that supplies data to the
program is known as the input stream. It reads the data from the file and hands it over to the program. The
stream that receives data from the program is known as output stream. It writes the received data to the file.
C++ comes with libraries which provides us many ways for performing input and output. In C++ input and
output is performed in the form of sequence of bytes or more commonly known as streams.
27 | P a g e

Input Stream: If the direction of flow of bytes is from device(for example: Keyboard) to the main memory
then this process is called input.
Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen )
then this process is called output.

9) Describe templates. Write about its advantages.


 A template is a simple and very powerful tool in C++. The idea is to pass data type as a parameter so that
we don’t need to write same code for different data types. For eg:- a software company may need sort ( )
function for different data types. Rather than writing and maintaining the multiple code, we can write on
sort ( ) function and pass the data as parameter. Templates provides great flexibility to the language. It was
not the original feature of C++ as it was added later on. The template functions are also called genric
functions and template class are also known as generic classes because they support any data type.
#Advantages:
 One C++ Class Template can handle different types of parameters.
 Compiler generates classes for only the used types. ...
 Templates reduce the effort on coding for different data types to a single set of code.
 Testing and debugging efforts are reduced.

10) Write short notes on abstract class and virtual base class.
 `An ambiguity can arise when several paths exist to a class from the same base class. This means that a
child class could have duplicate sets of members inherited from a single base class. - C++ solves this issue
by introducing a virtual base class.
In C++, we use terms abstract class and interface interchangeably. A class with pure virtual functionis known
as abstract class. For example the following function is a pure virtual function:

Virtual void fun() = 0;


A pure virtual function is marked with a virtual keyword and has = 0 after its signature. You can call this
function an abstract function as it has no body. The derived class must give the implementation to all the pure
virtual functions of parent class else it will become abstract class by default.

// Exampe up

You might also like