Answer the following questions
1. Explain the term Data
Abstraction in detail.
Humans use abstraction in order to manage complex situations. Objects and processes are reduced to basics and referred to in generic terms. Classes allow more direct use of the results of this type of abstraction in software development. The first step towards solving a problem is analysis. In object-oriented programming, analysis comprises identifying and describing objects and recognizing their mutual relationships. Object descriptions are the building blocks of classes.
In C++, a class is a user-defined type.
It contains data members, which describe the properties of the class, and
member functions, or methods, which describe the capacities of the objects.
Classes are simply patterns used to instantiate, or create, objects of the
class type. In other words, an object is a variable of a given class.
2. What are the benefits of OOP?
Moving to the advantages of OOP, we
would like to say that there are many as this is one of the core development
approaches which is widely accepted. Let’s see what the advantages of OOP are
offers to its users.
1. Re-usability
It means reusing some facilities rather
than building them again and again. This is done with the use of a class. We
can use it ‘n’ number of times as per our need.
2. Data Redundancy
This is a condition created at the
place of data storage (you can say Databases)where the same piece of data is
held in two separate places. So the data redundancy is one of the greatest
advantages of OOP. If a user wants a similar functionality in multiple classes,
he/she can go ahead by writing common class definitions for similar
functionalities and inherit them.
3. Code Maintenance
This feature is more of a necessity for
any programming languages; it helps users from doing re-work in many ways. It
is always easy and time-saving to maintain and modify the existing codes by
incorporating new changes into them.
4. Security
With the use of data hiding and
abstraction mechanism, we are filtering out limited data to exposure, which
means we are maintaining security and providing necessary data to view.
5. Design Benefits
If you are practicing on OOPs, the
design benefit a user will get is in terms of designing and fixing things
easily and eliminating the risks (if any). Here the Object-Oriented Programs
forces the designers to have a long and extensive design phase, which results
in better designs and fewer flaws. After a time when the program has reached
some critical limits, it is easier to program all the non-OOP’s one separately.
6. Better productivity
with the above-mentioned facts of using
the application definitely enhances its users overall productivity. This leads
to more work done, finishing a better program, having more inbuilt features,
and easier reading, writing and maintaining. An OOP programmer cans stitch new
software objects to make completely new programs. A good number of libraries
with useful functions in abundance make it possible.
7. Easy troubleshooting
lets witness some common issues or
problems any developers face in their work.
Is this the problem in the widget file?
Is the problem is in the WhaleFlumper?
Will I have to trudge through that
‘sewage.c’ file?
Commenting on all these issues related
to code.
So, many times, something has gone
wrong, which later becomes so brainstorming for the developers to look where
the error is. Relax! Working with OOP language, you will know where to look
for. This is the advantage of using encapsulation in OOP; all the objects are
self-constrained. With this modality behavior, the IT teams get a lot of work
benefits as they are now capable of working on multiple projects simultaneously
with an advantage that there is no possibility of code duplicity.
8. Polymorphism Flexibility
Let’s see a scenario to better explain
this behavior.
You behave in a different way if the
place or surrounding gets change. A person will behave like a customer if he is
in a market, the same person will behave like a student if he is in a school
and as a son/daughter if put in a house. Here we can see that the same person
showing different behavior every time the surroundings are changed. This means
polymorphism is flexible and helps developers in a number of ways.
It’s simplicity
Extensibility
9. Problems solving
Decomposing a complex problem into
smaller chunks or discrete components is a good practice. OOP is specialized in
this behavior, as it breaks down your software code into bite-sized – one
object at a time. The broken components can be reused in solutions to different
other problems (both less and more complex), or either they can be replaced by
the future modules that relate to the same interface with implementations
details.
3. Explain the following terms:
(a) Object
Object -- an encapsulation of data
along with functions that act upon that data.
An object consists of:
Name -- the variable name we give it
Member data -- the data that describes
the object
Member functions -- behavior aspects of
the object (functions related to the object itself)
(b) Class.
Class -- a blueprint for objects. A
class is a user-defined type that describes what a certain type of object will
look like. A class description consists of a declaration and a definition.
Usually these pieces are split into separate files.
An object is a single instance of a
class. You can create many objects from the same class type.
4. Explain basic data types in
C++.
C++ supports a wide variety of data
types and the programmer can select the data type appropriate to the needs of
the application. Data types specify the size and types of value to be stored.
However, storage representation and machine instructions to manipulate each
data type differ from machine to machine, although C++ instructions are
identical on all machines
Built in data types
char: For characters. Size 1 byte.
char ch = 'A';
int: For integers. Size 2 bytes.
int num = 100;
float: For single precision floating
point. Size 4 bytes.
float num = 123.78987;
double: For double precision floating
point. Size 8 bytes.
double num = 10098.98899;
bool: For booleans, true or false.
bool b = true;
wchar_t: Wide Character. This should be
avoided because its size is implementation defined and not reliable.
User-defined data types
We have three types of user-defined
data types in C++
1. struct
2. union
3. enum
Derived data types in C++
We have three types of derived-defined
data types in C++
1. Array
2. Function
3. Pointer
5. Explain the term Reference
Variable in detail.
Reference variable is an alternate name
of already existing variable. It cannot be changed to refer another variable
and should be initialized at the time of declaration and cannot be NULL. The
operator ‘&’ is used to declare reference variable.
The following is the syntax of
reference variable.
datatype variable_name; // variable
declaration
datatype& refer_var =
variable_name; // reference variable
Here,
datatype − The datatype of variable
like int, char, float etc.
variable_name − This is the name of
variable given by user.
refer_var − The name of reference
variable.
The following is an example of
reference variable.
Example
#include <iostream>
using namespace std;
int main() {
int a = 8;
int& b = a;
cout << "The
variable a : " << a;
cout << "\nThe
reference variable r : " << b;
return 0;
}
6.What is Operator? What are its
Types?
Operators are special type of
functions, that takes one or more arguments and produces a new value. For
example : addition (+), substraction (-), multiplication (*) etc, are all
operators. Operators are used to perform various operations on variables and constants.
Types of operators
Assignment Operator
Mathematical Operators
Relational Operators
Logical Operators
Bitwise Operators
Shift Operators
Unary Operators
Ternary Operator
Comma Operator
Assignment Operator (=)
Operates '=' is used for assignment, it
takes the right-hand side (called rvalue) and copy it into the left-hand side
(called lvalue). Assignment operator is the only operator which can be
overloaded but cannot be inherited.
Mathematical Operators
There are operators used to perform
basic mathematical operations. Addition (+) , subtraction (-) , diversion (/)
multiplication (*) and modulus (%) are the basic mathematical operators.
Modulus operator cannot be used with floating-point numbers.
C++ and C also use a shorthand notation
to perform an operation and assignment at same type. Example,
int x=10;
x += 4 // will add 4 to 10, and hence
assign 14 to X.
x -= 5 // will subtract 5 from 10 and
assign 5 to x.
Relational Operators
These operators establish a
relationship between operands. The relational operators are : less than (<)
, grater thatn (>) , less than or equal to (<=), greater than equal to
(>=), equivalent (==) and not equivalent (!=).
You must notice that assignment operator
is (=) and there is a relational operator, for equivalent (==). These two are
different from each other, the assignment operator assigns the value to any
Variables, whereas equivalent operator is used to compare values, like in
if-else conditions, Example
int x = 10; //assignment operator
x=5;
// again assignment operator
if(x == 5) // here we have
used equivalent relational operator, for comparison
{
cout
<<"Successfully compared";
}
Logical Operators
The logical operators are AND
(&&) and OR (||). They are used to combine two different expressions
together.
If two statement are connected using
AND operator, the validity of both statements will be considered, but if they
are connected using OR operator, then either one of them must be valid. These
operators are mostly used in loops (especially while loop) and in Decision
making.
Bitwise Operators
There are used to change individual
bits into a number. They work with only integral data types like char, int and
long and not with floating point values.
Bitwise AND operators &
Bitwise OR operator |
And bitwise XOR operator ^
And, bitwise NOT operator ~
They can be used as shorthand notation
too, & = , |= , ^= , ~= etc.
Shift Operators
Shift Operators are used to shift Bits
of any variable. It is of three types,
Left Shift Operator <<
Right Shift Operator >>
Unsigned Right Shift Operator
>>>
Unary Operators
These are the operators which work on
only one operand. There are many unary operators, but increment ++ and
decrement -- operators are most used.
Other Unary Operators : address of
&, dereference *, new and delete, bitwise not ~, logical not !, unary minus
- and unary plus +.
Ternary Operator
The ternary if-else ? : is an operator
which has three operands.
int a = 10;
a > 5 ? cout <<
"true" : cout << "false"
Comma Operator
This is used to separate variable names
and to separate expressions. In case of expressions, the value of last
expression is produced and used.
Example :
int a,b,c; // variables declaration
using comma operator
a=b++, c++; // a = c++ will be done.
7.Explain Scope Resolution
Operator with example.
The scope resolution operator ( :: ) is
used for several reasons. For example: If the global variable name is same as
local variable name, the scope resolution operator will be used to call the
global variable. It is also used to define a function outside the class and
used to access the static variables of class.
Here an example of scope resolution
operator in C++ language,
Example
#include <iostream>
using namespace std;
char a = 'm';
static int b = 50;
int main() {
char a = 's';
cout << "The
static variable : "<< ::b;
cout << "\nThe
local variable : " << a;
cout << "\nThe
global variable : " << ::a;
return 0;
}
8. Write a program to print year
is leap or not.
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a
year: ";
cin >> year;
// leap year if perfectly
divisible by 400
if (year % 400 == 0) {
cout << year
<< " is a leap year.";
}
// not a leap year if divisible
by 100
// but not divisible by 400
else if (year % 100 == 0) {
cout << year
<< " is not a leap year.";
}
// leap year if not divisible by
100
// but divisible by 4
else if (year % 4 == 0) {
cout << year
<< " is a leap year.";
}
// all other years are not leap
years
else {
cout << year
<< " is not a leap year.";
}
return 0;
}
9.What do you mean by dynamic
initialization of a variable? Give an example.
Dynamic initialization of object refers
to initializing the objects at run time i.e. the initial value of an object is
to be provided during run time. Dynamic initialization can be achieved using
constructors and passing parameters values to the constructors. This type of
initialization is required to initialize the class variables during run time.
Dynamic initialization of objects is
needed as
It utilizes memory efficiently.
Various initialization formats can be
provided using overloaded constructors.
It has the flexibility of using
different formats of data at run time considering the situation.
Example Code
#include <iostream>
using namespace std;
class simple_interest {
float principle , time,
rate ,interest;
public:
simple_interest
(float a, float b, float c) {
principle = a;
time
=b;
rate
= c;
}
void display ( ) {
interest =(principle* rate* time)/100;
cout<<"interest ="<<interest ;
}
};
int main() {
float p,r,t;
cout<<"principle amount, time and rate"<<endl;
cout<<"2000 7.5
2"<<endl;
simple_interest
s1(2000,7.5,2);//dynamic initialization
s1.display();
return 1;
}
10.What is access specifier?
Enlist them.
The public keyword is an access
specifier. Access specifiers define how the members (attributes and methods) of
a class can be accessed. In the example above, the members are public - which
means that they can be accessed and modified from outside the code.
However, what if we want members to be
private and hidden from the outside world?
In C++, there are three access
specifiers:
public - members are accessible from
outside the class
private - members cannot be accessed
(or viewed) from outside the class
protected - members cannot be accessed
from outside the class, however, they can be accessed in inherited classes.
11.Explain different types of
Inheritance with example.
Single Inheritance: In this type of
Inheritance, only one class is derived from a single class (Base class). In an
example below, Class B is derived from Class A. That means Class B will be
having access to data members and member functions of Class A. Another example
can be oe student can have only one id in college to access its information.
enter image description here
Multiple Inheritance: In this type of
Inheritance, a class is derived from more than one super class. There can be
more than one Super class and only one derived class. One derived class will
implement properties of many Super classes. In this example, Class A extends
properties of 3 Super Class, Class B, Class C and Class D. Another example can
be many students belong to only one college.
enter image description here
Hierarchical Inheritance: In this type
of Inheritance, one super class can have multiple deriving classes. There can
be many classes deriving only one super Class. In this example, Class A is
having 3 derived classes Class B, Class C and Class D. 3 derived classes will
extend prosperities of single base class, Class A. Another example can be One
Universities can have multiple colleges affiliated.
enter image description here
Multilevel Inheritance: In this type of
Inheritance, Classes are inherited in the form of levels. For example, figure
shows that Class C is derived from Class B and Class B is derived from Class A.
Therefore , Inheritance can be carried out in multiple levels.
enter image description here
The derived class with multilevel
inheritance can be declared as follows:
class A{……..};
class B extends A{….};
class C extends B{….};
The process can be extended to any
number of levels.
Hybrid Inheritance: Sometimes, there is
a need to implement more than one type of inheritances. In such situations, we
combine two or more types of inheritances and design a Hybrid Inheritance.
Given figure shows, Class B and Class D have single Inheritance designed,
whereas Class A has two derived classes class B and Class C. In this Hybrid
Inheritance has been carried out combining Single and Multiple Inheritance.
12.When do we make a class
Virtual?
- 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. When a class is made virtual, necessary care is taken so
that the duplication is avoided regardless of the number of paths that exist to
the child class.
- When two or more objects are derived
from a common base class, we can prevent multiple copies of the base class
being present in an object derived from those objects by declaring the base
class as virtual when it is being inherited. Such a base class is known as
virtual base class. This can be achieved by preceding the base class’ name with
the word virtual.
13.What is Polymorphism? What is
the difference between Compile Time and Runtime Polymorphism.
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. A real-life example of
polymorphism is a person who at the same time can have different
characteristics. Like a man at the same time is a father, a husband and an
employee. So the same person exhibits 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
Polymorphism-in-CPP
Types of Polymorphism
Compile-time polymorphism: This type of
polymorphism is achieved by function overloading or operator overloading.
Function Overloading: When there are
multiple functions with the same name but different parameters, then the
functions are said to be overloaded. Functions can be overloaded by changing
the number of arguments or/and changing the type of arguments.
Operator Overloading: C++ also provides
the option to overload operators. For example, we can make use of the addition
operator (+) for string class to concatenate two strings. We know that the task
of this operator is to add two operands. So a single operator ‘+’, when placed
between integer operands, adds them and when placed between string operands,
concatenates them.
Runtime polymorphism: This type of
polymorphism is achieved by Function Overriding.
Function overriding 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.
14.What is a Function Template?
Write a function template for finding the largest number in a given array. The
array parameter must be of generic data types.
A template is a simple yet very
powerful tool in C++. The simple idea is to pass data type as a parameter so
that we don’t need to write the same code for different data types. For
example, a software company may need to sort() for different data types. Rather
than writing and maintaining multiple codes, we can write one sort() and pass
data type as a parameter.
C++ adds two new keywords to support
templates: ‘template’ and ‘typename’. The second keyword can always be replaced
by the keyword ‘class’.
Program Source Code:
#include<iostream>
using namespace std;
#define N 10
// defining the function template that
// returns the largest number of the
array
// we consider type of array size
directly integer
template <class T>
T find_max(T t[], int NO_OF_TERMS){
T temp_max = t[0];
for (int i = 0; i < NO_OF_TERMS; i++)
{
if (temp_max < t[i] )
{
temp_max = t[i];
}
}
return temp_max;
}
int main(){
int numbers[N];
cout<<"Enter numbers:"<<endl;
for (int i = 0; i < N; i++)
{
cin>>numbers[i];
}
cout<<"Largest Number of array
is:"<<find_max(numbers,N)<<endl;
// though you can make array size dynamic
return 0;
}
15.Friend Class
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.
A friend class can access both private
and protected members of the class in which it has been declared as friend.
class Node {
private:
int key;
Node* next;
/* Other members of Node
Class */
// Now class
LinkedList can
// access private members
of Node
friend class LinkedList;
};
16.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.
Any change to an inline function could
require all clients of the function to be recompiled because compiler would
need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword
inline before the function name and define the function before any calls are
made to the function. The compiler can ignore the inline qualifier in case
defined function is more than a line.
A function definition in a class
definition is an inline function definition, even without the use of the inline
specifier.
Following is an example, which makes
use of inline function to return max of two numbers −
#include <iostream>
using namespace std;
inline int Max(int x, int y) {
return (x > y)? x : y;
}
// Main function for the program
int main() {
cout << "Max
(20,10): " << Max(20,10) << endl;
cout << "Max
(0,200): " << Max(0,200) << endl;
cout << "Max
(100,1010): " << Max(100,1010) << endl;
return 0;
}
0 Comments