C Answers
C Answers
Data hiding also reduces system complexity for increased robustness by limiting
interdependencies between software components.
private - makes the data members hidden to all code outside the class scope.
protected - makes the data members hidden to all code outside the class scope and scope of the
derived classes.
You can further hide to restrict visibility of variables to it’s current file, using static.
Q2. Define Polymorphism. What are the techniques used in C++ to achieve this?
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form.
Real life example of polymorphism, a person at the same time can have different characteristic.
Like a man at the same time is a father, a husband, an employee. So the same person posses
different behavior in different situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object Oriented Programming.
In C++ polymorphism is mainly divided into two types:
Compile time Polymorphism
Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved by function overloading
or operator overloading.
1.
Function Overloading: When there are multiple functions with same name but
different parameters then these functions are said to be overloaded. Functions can be
overloaded by change in number of arguments or/and change in type of
arguments.
Rules of Function Overloading
filter_none
edit
play_arrow
brightness_4
// C++ program for function overloading
#include <bits/stdc++.h>
int main() {
Geeks obj1;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
Output:
12 + i9
In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition
operator and can add two numbers(integers or floating point) but here the operator is
made to perform addition of two imaginary or complex numbers. To learn operator
overloading in details visit this link.
2. Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.
Function overriding on the other hand occurs when a derived class has a definition
for one of the member functions of the base class. That base function is said to
be overridden.
filter_none
edit
play_arrow
brightness_4
// C++ program for function overriding
#include <bits/stdc++.h>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
void show ()
{ cout<< "show derived class" <<endl; }
};
//main function
int main()
{
base *bptr;
derived d;
bptr = &d;
return 0;
}
Output:
print derived class
show base class
Q3. How are inline functions implemented in C++. What are its merits and limitations?
Inline function is one of the important feature of C++. So, let’s first understand why inline
functions are used and what is the purpose of inline function?
When the program executes the function call instruction the CPU stores the memory address of
the instruction following the function call, copies the arguments of the function on the stack and
finally transfers control to the specified function. The CPU then executes the function code,
stores the function return value in a predefined memory location/register and returns control to
the calling function. This can become overhead if the execution time of function is less than the
switching time from the caller function to called function (callee). For functions that are large
and/or perform complex tasks, the overhead of the function call is usually insignificant compared
to the amount of time the function takes to run. However, for small, commonly-used functions,
the time needed to make the function call is often a lot more than the time needed to actually
execute the function’s code. This overhead occurs for small functions because execution time of
small function is less than the switching time.
C++ provides an inline functions to reduce the function call overhead. Inline function is a
function that is expanded in line when it is called. When the inline function is called whole code
of the inline function gets inserted or substituted at the point of inline function call. This
substitution is performed by the C++ compiler at compile time. Inline function may increase
efficiency if it is small.
The syntax for defining the function inline is:
inline return-type function-name(parameters)
{
// function code
}
Remember, inlining is only a request to the compiler, not a command. Compiler can ignore the
request for inlining. Compiler may not perform inlining in such circumstances like:
1) If a function contains a loop. (for, while, do-while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return statement doesn’t exist in function
body.
5) If a function contains switch or goto statement.
Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform context specific
optimization on the body of function. Such optimizations are not possible for normal function
calls. Other optimizations can be obtained by considering the flows of calling context and the
called context.
5) Inline function may be useful (if it is small) for embedded systems because inline can yield
less code than the function call preamble and return.
Inline function disadvantages:
1) The added variables from the inlined function consumes additional registers, After in-lining
function if variables number which are going to use register increases than they may create
overhead on register variable resource utilization. This means that when inline function body is
substituted at the point of function call, total number of variables used by the function also gets
inserted. So the number of register going to be used for the variables will also get increased. So if
after function inlining variable numbers increase drastically then it would surely cause an
overhead on register utilization.
2) If you use too many inline functions then the size of the binary executable file will be large,
because of the duplication of same code.
3) Too much inlining can also reduce your instruction cache hit rate, thus reducing the speed of
instruction fetch from that of cache memory to that of primary memory.
4) Inline function may increase compile time overhead if someone changes the code inside the
inline function then all the calling location has to be recompiled because compiler would require
to replace all the code once again to reflect the changes, otherwise it will continue with old
functionality.
5) Inline functions may not be useful for many embedded systems. Because in embedded
systems code size is more important than speed.
6) Inline functions might cause thrashing because inlining might increase size of the binary
executable file. Thrashing in memory causes performance of computer to degrade.
Q4. How is polymorphism achieved at run time. Explain with the help of a program?
Ans.
Runtime Polymorphism
In case of function overriding we have two definitions of the same function, one is parent class
and one in child class. The call to the function is determined at runtime to decide which
definition of the function is to be called, thats the reason it is called runtime polymorphism.
#include <iostream>
using namespace std;
class A {
public:
void disp(){
cout<<"Super Class Function"<<endl;
}
};
class B: public A{
public:
void disp(){
cout<<"Sub Class Function";
}
};
int main() {
//Parent class object
A obj;
obj.disp();
//Child class object
B obj2;
obj2.disp();
return 0;
}
Output:
Q5. What is run time memory management in C++.What support is provided by c++ for
this and how does it differ from C’s memory management?
Ans.
new operator
The new operator denotes a request for memory allocation on the Heap. If sufficient memory is
available, new operator initializes the memory and returns the address of the newly allocated and
initialized memory to the pointer variable.
Syntax to use new operator: To allocate memory of any data type, the syntax is:
pointer-variable = new data-type;
Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data
type including array or any user defined data types including structure and class.
Example:
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
Example:
// It will free the entire array
// pointed by p.
delete[] p;
// C++ program to illustrate dynamic allocation
// and deallocation of memory using new and delete
#include <iostream>
using namespace std;
int main ()
{
// Pointer initialization to null
int* p = NULL;
if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;
return 0;
}
Output:
Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5
Q6. What is operator overloading ?What are the methods of overloading the operators in
C++? Explain one method of operator overloading in C++ with example.?
Ans. In C++, it's possible to change the way operator works (for user-defined types). In this
article, you will learn to implement operator overloading feature.
The meaning of an operator is always same for variable of basic types like: int, float, double etc.
For example: To add two integers, + operator is used.
However, for user-defined types (like: objects), you can redefine the way operator works. For
example:
If there are two objects of a class that contains string as its data members. You can redefine the
meaning of + operator and use it to concatenate those strings.
This feature in C++ programming that allows programmer to redefine the meaning of an operator
(when they operate on class objects) is known as operator overloading.
to
calculation = (a*b)+(a/b);
How to overload operators in C++ programming?
To overload an operator, a special operator function is defined inside the class as:
class className
{
... .. ...
public
returnType operator symbol (arguments)
{
... .. ...
}
... .. ...
};
class Test
{
private:
int count;
public:
Test(): count(5){}
int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}
Q7. Write a program which implements the concept of virtual base class?
Ans. #include<iostream.h>
#include<conio.h>
class student {
int rno;
public:
void getnumber() {
cout << "Enter Roll No:";
cin>>rno;
}
void putnumber() {
cout << "\n\n\tRoll No:" << rno << "\n";
}
};
void getmarks() {
cout << "Enter Marks\n";
cout << "Part1:";
cin>>part1;
cout << "Part2:";
cin>>part2;
}
void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};
void getscore() {
cout << "Enter Sports Score:";
cin>>score;
}
void putscore() {
cout << "\n\tSports Score is:" << score;
}
};
void display() {
total = part1 + part2 + score;
putnumber();
putmarks();
putscore();
cout << "\n\tTotal Score:" << total;
}
};
void main() {
result obj;
clrscr();
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
getch();
}
Sample Output
Enter Marks
Part1: 90
Part2: 80
Enter Sports Score: 80
Ans. Files are a means to store data in a storage device. C++ file handling provides a mechanism
to store output of a program in a file and read from a file on the disk. So far, we have been
using <iostream> header file which provide functions cin and coutto take input from console
and write output to a console respectively. Now, we introduce one more header
file <fstream>which provides data types or classes ( ifstream , ofstream , fstream ) to read
from a file and write to a file.
Mode Explanation
ios :: ate File pointer moves to the end of the file but allows to writes data
in any location in the file
If a file is opened in ios :: out mode, then by default it is opened in ios :: trunc mode also i.e the
contents of the opened file is overwritten. If we open a file using ifstream class, then by default
it is opened in ios :: in mode and if we open a file using ofstream class, then by default it is
opened in ios :: out mode. The fstream class doesn’t provide any default mode.
Q9.What are input and output streams. Describe various classes available for file
operations?
Ans. 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.
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.
Header files available in C++ for Input – Output operation are:
iostream: iostream stands for standard input output stream. This header file contains
definitions to objects like cin, cout, cerr etc.
iomanip: iomanip stands for input output manipulators. The methods declared in this files
are used for manipulating streams. This file contains definitions of setw, setprecision etc.
fstream: This header file mainly describes the file stream. This header file is used to
handle the data being read from a file as input or data being written into the file as output.
In C++ articles, these two keywords cout and cin are used very often for taking inputs and
printing outputs. These two are the most basic methods of taking input and output in C++. For
using cin and cout we must include the header file iostream in our program.
Standard output stream (cout): Usually the standard output device is the display
screen. cout is the instance of the ostream class. cout is used to produce output on the standard
output device which is usually the display screen. The data needed to be displayed on the screen
is inserted in the standard output stream (cout) using the insertion operator (<<).
standard input stream (cin): Usually the input device is the keyboard. cin is the instance of the
class istream and is used to read input from the standard input device which is usually keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.
Ans. Friend Class 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 Node
private:
int key;
Node *next;
};
Friend Function Like friend class, a friend function can be given special grant to access private
and protected members. A friend function can be:
a) A method of another class
b) A global function
class Node
private:
int key;
Node *next;
};
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of encapsulation
of separate classes in object-oriented programming.
2) Friendship is not mutual. If a class A is friend of B, then B doesn’t become friend of A
automatically.
3) Friendship is not inherited (See this for more details)
4) The concept of friends is not there in Java.
Q11.What are the main advantages of passing arguments by reference. Explain with the help of
an example?
Ans.
1. No new copy of variable is made, so overhead of copying is saved. This Makes program
execute faster specially when passing object of large structs or classes.
2. Array or Object can be pass
3. Sometimes function need to change the original value(eg. Sorting an array, swapping) and
sometimes changing value inside function is useful.
4. Can return multiple values from a function.
PROGRAM:-
#include <iostream>
// function declaration
int main () {
int a = 100;
int b = 200;
swap(a, b);
return 0;
}
Q12. Write a program in C++ to sort an array of integers using insertion sort?
Ans.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int size, arr[50], i, j, temp;
cout<<"Enter Array Size : ";
cin>>size;
cout<<"Enter Array Elements : ";
for(i=0; i<size; i++)
{
cin>>arr[i];
}
cout<<"Sorting array using selection sort ... \n";
for(i=1; i<size; i++)
{
temp=arr[i];
j=i-1;
while((temp<arr[j]) && (j>=0))
{
arr[j+1]=arr[j];
j=j-1;
}
arr[j+1]=temp;
}
cout<<"Array after sorting : \n";
for(i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
getch();
}
Q13. Write a program in c++ to calculate the sum of odd & even numbers in an array
Ans.
#include <iostream>
// Driver function
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
EvenOddSum(arr, n);
return 0;
}
Ans.
#include <iostream>
1.
2. int main()
3. {
4. int arr[100];
5. int size, i, j, temp;
6.
7. // Reading the size of the array
8. cout<<"Enter size of array: ";
9. cin>>size;
10.
11. //Reading elements of array
12. cout<<"Enter elements in array: ";
13. for(i=0; i<size; i++)
14. {
15. cin>>arr[i];
16. }
17. //Sorting an array in ascending order
18. for(i=0; i<size; i++)
19. {
20. for(j=i+1; j<size; j++)
21. {
22. //If there is a smaller element found on right of the array then swap it.
23. if(arr[j] < arr[i])
24. {
25. temp = arr[i];
26. arr[i] = arr[j];
27. arr[j] = temp;
28. }
29. }
30. }
Q15. Write a program to print highest and second highest element of an array?
Ans.
#include<iostream>
#include<conio.h>
void main()
{
int a[10], i, largest = 0, second_largest = 0, pos1, pos2;
int n;
cout << "Enter Number of elements :";
cin>>n;
for (i = 0; i<n; ++i)
{
cout << "n Enter " << (i + 1) << "th Element :";
cin >> a[i];
}
//Finding Largest
for (i = 0; i<10; ++i)
{
if (a[i]>largest)
{
largest = a[i];
pos1 = i;
}
}
//finding second largset
for (i = 0; i<10; ++i)
{
if (a[i]>second_largest)
{
if (a[i] == largest)
continue; //Ignoring largest in order to get second largest
second_largest = a[i];
pos2 = i;
}
}
cout << "nn Largest Number :" << largest << " at position " << (pos1 + 1);
cout << "nn Second Largest Number :"<< second_largest << " at position " << (pos2 + 1);
getch();
return;
}
Q16. Write a program in C++ to find area of a circle , rectangle and triangle by
overloading the function area()?
Ans.
#include<iostream.h>
#include<conio.h>
class over
{
float l,b,r,area;
public:
void volume(float,float);
void volume(float);
};
void over::volume(float l, float b)
{
cout<<"Area of rectangle = "<<l*b;
void over::volume(float r)
{
cout<<"Area of circle = "<<3.14*r*r;
}
void main()
{
over o;
clrscre():
float r,l,b;
cout<<"\nEnter radius: ";
cin>>r;
o.volume(r);
cout<<"\n\nEnter lenght and breadth: ";
cin>>l>>b;
o.volume(l,b);
getch();
}
Ans.
Function Description
#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream fp;
char buf[100];
int pos;