Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Wa0003.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Unit – 1 - Principles of Object – Oriented Programming Tokens, Expressions & Control

Statements

Q–1 Explain Object Oriented Programming Paradigm.

Ans. Programming paradigms

A programming paradigm is a model of programming based on distinct concepts that


shapes the way programmers design, organize and write programs.

Object-Oriented Programming Paradigm

 The major motivating factor in the invention of object-oriented approach is to


remove some of the flaws encountered in the procedural approach.

 OOP treats data as a critical element in the program development and does not
allow it to flow freely around the systems.

 It ties data more closely to the functions that operate on it, and protects it from
accidental modification from outside functions.

 OOP allows decomposition of a problem into a number of entities called objects


and then builds data and functions around these objects.

 The data of an object can be accessed only by the function associated with that
object.

 However, functions of one object can access the the functions of other objects.

Some of the striking features of object-oriented programming are

 Emphasis is on data rather than procedure.

 Programs are divided into what are known as objects.

 Data structures are designed such that they characterize the objects.

 Data is hidden and cannot be accessed by external functions.


 Objects may communicate with each other through functions.

 New data and functions can be easily added whenever necessary.

 Follows bottom-up approach in program design.

Q–2 Explain basic concepts of Object Oriented Programming.

Ans. Before starting to learn C++ it is essential to have a basic knowledge of the concepts of
Object oriented programming. Some of the important object oriented features are
namely:

 Objects

 Classes

 Inheritance

 Data Abstraction

 Data Encapsulation

 Polymorphism

 Overloading

 Reusability

In order to understand the basic concepts in C++, a programmer must have a good
knowledge of the basic terminology in object-oriented programming. Below is a brief
outline of the concepts of object-oriented programming languages:

Objects:

Object is the basic unit of object-oriented programming. Objects are identified by its
unique name. An object represents a particular instance of a class. There can be more
than one instance of a class. Each instance of a class can hold its own relevant data.

An Object is a collection of data members and associated member functions also known
as methods.

Classes:

Classes are data types based on which objects are created. Objects with similar
properties and methods are grouped together to form a Class. Thus a Class represents a
set of individual objects. Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects become functions of the class
and are referred to as Methods.

No memory is allocated when a class is created. Memory is allocated only when an


object is created, i.e., when an instance of a class is created.
Inheritance:

Inheritance is the process of forming a new class from an existing class or base class.
The base class is also known as parent class or super class. The new class that is
formed is called derived class. Derived class is also known as a child class or sub class.
Inheritance helps in reducing the overall code size of the program, which is an
important concept in object-oriented programming.

Data Abstraction:

Data Abstraction increases the power of programming language by creating user defined
data types. Data Abstraction also represents the needed information in the program
without presenting the details.

Data Encapsulation:

Data Encapsulation combines data and functions into a single unit called Class. When
using Data Encapsulation, data is not accessed directly; it is only accessible through the
functions present inside the class. Data Encapsulation enables the important concept of
data hiding possible.

Polymorphism:

Polymorphism allows routines to use variables of different types at different times. An


operator or function can be given different meanings or functions. Polymorphism refers
to a single function or multi-functioning operator performing in different ways.

Overloading:

Overloading is one type of Polymorphism. It allows an object to have different


meanings, depending on its context. When an existing operator or function begins to
operate on new data type, or class, it is understood to be overloaded.

Reusability:

This term refers to the ability for multiple programmers to use the same written and
debugged existing class of data. This is a time saving device and adds code efficiency to
the language. Additionally, the programmer can incorporate new features to the existing
class, further developing the application and allowing users to achieve increased
performance. This time saving feature optimizes code, helps in gaining secured
applications and facilitates easier maintenance on the application.

The implementation of each of the above object-oriented programming features for C++
will be highlighted in later sections.

Q–3 Explain benefits/advantages of Object Oriented Programming.

Ans. Object-oriented programming technique is the latest programming approach used by


the programmers to develop modern day application. It is based on the principle of
data hiding, abstraction, encapsulation, inheritance and polymorphism.

The advantages of object oriented programming language are as follow :

 The programmers written with OOP are really easy to understand.

 It is good for defining abstract data types.

 Since everything is treated as objects, so we can model a real-world concept


using OOP.

 OOP approach offers the reusability of classes. We can reuse the classes that are
already created without writing them again and again.
 It is easy to maintain and modify existing code as new objects can be created
with small differences to existing ones.

 Since the parallel development of classes is possible in OOP concept, It results in


the quick development of the complete programmes.

 Programmers written in OOP technique are marginally easier to test, manage as


well as maintain.

 It is a secured development technique since data is hidden and can’t be accessed


by external functions.

Q–4 What is C++? Explain structure of C++ program.

Ans. C++ is a programming language developed by Bjarne Stroustrup in 1979 at Bell Labs.
C++ is regarded as a middle-level language, as it comprises a combination of both high-
level and low-level language features. It is a superset of C, and that virtually any legal C
program is a legal C++ program. C++ runs on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.

A C++ program involves the following section:

 Documentation Section

 Header File Declaration Section

 Global Declaration Section

 Class Declaration and Member Function Definition Section

 Main Function

 Function Definition Section

Section 1 : Documentation Section

/* Comments */

This is a comment block, which is ignored by the compiler. Comment can be used
anywhere in the program to add info about program or code block, which will be helpful
for developers to easily understand the existing code in the future.

Section 2 : Header File Declaration Section

 Header files used in the program are listed here.

 Header File provides Prototype declaration for different library functions.

 We can also include user define header file.

 Basically all preprocessor directives are written in this section.

Section 3 : Global Declaration Section

 Global Variables are declared here.

 Global Declaration may include –

o Declaring Structure

o Declaring Class

o Declaring Variable

Section 4 : Class Declaration Section


 Actually this section can be considered as sub section for the global declaration
section.

 Class declaration and all methods of that class are defined here.

Section 5 : Main Function

 Each and every C++ program always starts with main function.

 This is entry point for all the function. Each and every method is called indirectly
through main.

 We can create class objects in the main.

 Operating system call this function automatically.

Section 6 : Function Definition Section

 This is optional section. Generally this method was used in C Programming.

Q–5 Explain Input-Output operators.

Ans. In C++, input and output (I/O) operators are used to take input and display output. The
operator used for taking the input is known as the extraction or get from operator
(>>), while the operator used for displaying the output is known as the insertion or
put to operator (<<).

Input Operator

The input operator, commonly known as the extraction operator (>>), is used with the
standard input stream, cin. As stated earlier, cin treats data as a stream of characters.
These characters flow from cin to the program through the input operator. The input
operator works on two operands, namely, the c in stream on its left and a variable on its
right. Thus, the input operator takes (extracts) the value through cin and stores it in the
variable.

The input operator (">>") ("get from"), also known as stream extraction operator is
used to read a value from standard input.

Output Operator

The output operator, commonly known as the insertion operator (<<), is used. The
standard output stream cout like cin, cout also treats data as a stream of characters.
These characters flow from the program to cout through the output operator. The
output operator works on two operands, namely, the cout stream on its left and the
expression to be displayed on its right. The output operator directs (inserts) the value to
cout.

The output operator ("<<") ("put to"), also called stream insertion operator is used to
direct a value to standard output.

Q–6 Explain namespace.

Ans. Namespaces provide a scope for identifiers (variables, functions etc) within own
declarative region. Namespaces are used to systematize code in logical groups which
prevents naming conflict, which can occur especially if there are multiple libraries with
single names in your code base. On the namespace scope, all identifiers can be visible
for one another without qualification. In brief, the namespace defines a scope.

Defining a Namespace

The keyword namespace is used to define a namespace followed by the name of the
namespace. Here is the format:

Syntax:

namespace namespace_name {

// code declarations

Example:

namespace salary

int make_money();

int check_money();

//so forth....

The using Directive

The using directive permits all the names in a namespace to be applied without the
namespace-name as an explicit qualifier. Programmers can also avoid pre-awaiting of
namespaces with the using namespace directive. Using tells the compiler that
subsequent code is making use of names in an identified namespace.

Program showing the use of Namespace in C++:

Example:

#include<iostream>
using namespace std;
// first name space
namespace firstone
{
void fun()
{
cout << "This is the first NS" << endl;
}
}
// second name space
namespace secondone
{
void fun()
{
cout << "This is the second NS" << endl;
}
}

using namespace firstone;


int main()
{
// calls the function from first namespace.
fun();
}
Output:
This is the first NS
Q–7 Explain different tokens in brief.

Ans. Each word and punctuation is referred to as a token in C++. Tokens are the smallest
building block or smallest unit of a C++ program.

These following tokens are available in C++:

 Identifiers

 Keywords

 Constants

 Operators

 Strings

Identifiers

Identifiers are names given to different entries such as variables, structures, and
functions. Also, identifier names should have to be unique because these entities are
used in the execution of the program.

Keywords

Keywords are reserved words which have fixed meaning, and its meaning cannot be
changed. The meaning and working of these keywords are already known to the
compiler. C++ has more numbers of keyword than C, and those extra ones have special
working capabilities.

Operators

C++ operator is a symbol that is used to perform mathematical or logical manipulations.

Constants

Constants are like a variable, except that their value never changes during execution
once defined.

Strings

Strings are objects that signify sequences of characters.

Q–8 Explain different operators of C++.

Ans. Scope resolution operator


Scope resolution operator (::) in C++ programming language is used to define a
function outside a class or when we want to use a global variable but also has a local
variable with the same name. It is usually a binary operator which takes two inputs i.e.
one before it and one after it. It is used to associate a part of the program to a
particular scope which means that it can be used to recognize or relate any variable,
function etc. to another part of the program.
To distinguish between the normal functions and the member functions of the class, one
needs to use the scope resolution operator (::) in between the class name and the
member function name

i.e. Account::getBalance()

where Account is a class and getBalance() is a member function of the class Account.

Member Referencing Operator

C++ Member (dot & arrow) Operators


The . (dot) operator and the -> (arrow) operator are used to reference individual
members of classes, structures, and unions.

The dot operator is applied to the actual object. The arrow operator is used with a
pointer to an object. For example, consider the following class −

class Employee {
public:
char first_name[16];
int age;
} emp;

The (.) dot operator

To assign the value "zara" to the first_name member of object emp, you would write
something as follows:

strcpy(emp.first_name, "zara");

The (->) arrow operator

If p_emp is a pointer to an object of type Employee, then to assign the value "zara" to
the first_name member of object emp, you would write something as follows:

strcpy(p_emp->first_name, "zara");

The -> is called the arrow operator. It is formed by using the minus sign followed by a
greater than sign.

Simply saying: To access members of a structure, use the dot operator. To access
members of a class through a pointer, use the arrow operator.

Memory Management Operators

C++ new operator

Dynamic memory allocation means creating memory at runtime. For example, when we
declare an array, we must provide size of array in our source code to allocate memory
at compile time.

But if we need to allocate memory at runtime me must use new operator followed by
data type. If we need to allocate memory for more than one element, we must provide
total number of elements required in square bracket[ ]. It will return the address of first
byte of memory.

Syntax of new operator

ptr = new data-type;


//allocte memory for one element

ptr = new data-type [ size ];


//allocte memory for fixed number of element

C++ delete operator


Delete operator is used to deallocate the memory created by new operator at run-time.
Once the memory is no longer needed it should by freed so that the memory becomes
available again for other request of dynamic memory.
Syntax of delete operator

delete ptr;
//deallocte memory for one element

delete[] ptr;
//deallocte memory for array

Manipulators

Manipulators are operators used in C++ for formatting output. The data is
manipulated by the programmer's choice of display.

Some of the more commonly used manipulators are given below:

endl Manipulator

endl is the line feed operator in C++. It acts as a stream manipulator whose purpose is
to feed the whole line and then point the cursor to the beginning of the next line. We
can use \n (\n is an escape sequence) instead of endl for the same purpose.

setw Manipulator

This manipulator sets the minimum field width on output.

Syntax:

setw(x)

Example:

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
float basic, ta,da,gs;
basic=10000; ta=800; da=5000;
gs=basic+ta+da;
cout<<setw(10)<<"Basic"<<setw(10)<<basic<<endl
<<setw(10)<<"TA"<<setw(10)<<ta<<endl
<<setw(10)<<"DA"<<setw(10)<<da<<endl
<<setw(10)<<"GS"<<setw(10)<<gs<<endl;
return 0;
}

Q–9 Explain switch…case control structure with example.

Ans. It is a multi branch statement which can be used to select and execute one of the
available statements.

switch(value)

case 1: statement 1; break;


case 2: statement 2; break;

case n: statement n; break;

default: statement d;

Where value can be a variable of type numeric or character. The case label 1 to n can
also be written with constant identifiers.

When the value assigned matches with case label 1 statement 1 is executed. The break
statement written after statement 1 transfers the control out of the switch statement.
When the value doesn’t match with case label 1 then it checks with case label 2 and so
on. When the value assigned doesn’t match with any of the case labels (1 to n) then the
default clause is considered and the statement d is executed.

Q – 10 Explain while loop with syntax and example.

Ans. A while loop is a simple loop that will run the same code over and over as long as a
given conditional is true. The condition is checked at the beginning of each run through
the loop ( including the first one ). If the conditional is false for the beginning, the while
loop will be skipped all together.

while ( conditional ) {
// loop body
}

Q – 11 Explain the main( ) function.

Ans. The main() function

When a program begins running, the system calls the function main, which marks the
entry point of the program. By default, main has the storage class extern. Every
program must have one function named main, and the following constraints apply:

 No other function in the program can be called main.

 main cannot be defined as inline or static.

 main cannot be called from within a program.

 The address of main cannot be taken.

 The main function cannot be overloaded.

The function main can be defined with or without parameters, using any of the following
forms:

int main (void){}

int main ( ){}

int main(int argc, char *argv[]){}

int main (int argc, char ** argv){}

Q – 12 Explain function prototype.

Ans. A function prototype is a declaration of the function that tells the program about the
type of the value returned by the function and the number and type of arguments.

Function prototyping is one very useful feature of C++ function. A function prototype
describes the function interface to the compiler by giving details such as the number
and type of arguments and the type of return value.
The prototype declaration looks just like a function definition except that it has no body
i.e., its code is missing. This is the time you knew the difference between a declaration
and a definition.

A declaration introduces a (function) name to the program whereas a definition is a


declaration that also tells the program what the function is doing and how it is doing.

Thus the above given examples are function definitions and the following are
declarations or shall we say, function prototypes :

int absval(int a);

int gcd(int n1, int n2);

Therefore, you can say that a function prototype has the following parts :

 return type

 name of the function

 argument list

Q – 13 Explain call by reference with example.

Ans. In call by reference, original value is changed or modified because we pass reference
(address). Here, address of the value is passed in the function, so actual and formal
arguments share the same address space. Hence, any value changed inside the
function, is reflected inside as well as outside the function.

Pass-by-references is more efficient than pass-by-value, because it does not copy the
arguments. The formal parameter is an alias for the argument. When the called function
read or write the formal parameter, it is actually read or write the argument itself.

The difference between pass-by-reference and pass-by-value is that modifications made


to arguments passed in by reference in the called function have effect in the calling
function, whereas modifications made to arguments passed in by value in the called
function can not affect the calling function. Use pass-by-reference if you want to modify
the argument value in the calling function. Otherwise, use pass-by-value to pass
arguments.

Q – 14 Explain return by reference with suitable example.

Ans. As a function can be created to return a value of a primitive type, a function can also be
defined to return a reference to a primitive type. When declaring such a function, you
must indicate that it is returning a reference by preceding it with the & operator. Here is
an example:

double & GetWeeklyHours()

In the body of the function, defined the desired behavior of the function as you see fit.
The most important rule to apply is that the function must return not only a reference
but a reference to the appropriate type. When returning the value, don't precede the
name of the variable with &. Here is an example:

double & GetWeeklyHours()

double h = 46.50;
double &hours = h;

return hours;

When calling a function that returns a reference, you can proceed as if it returns a
regular value but of the appropriate type. Here is an example:

//---------------------------------------------------------------------------

#include <iostream>
using namespace std;
double & GetWeeklyHours()
{
double h = 46.50;
double &hours = h;
return hours;
}
//---------------------------------------------------------------------------
int main()
{
double hours = GetWeeklyHours();
cout << "Weekly Hours: " << hours << endl;
return 0;
}
//---------------------------------------------------------------------------
This would produce:
Weekly Hours: 46.5
Q – 15 What is inline function? Explain with example.

Ans. Inline function is a function which when invoked requests the compiler to replace the
calling statement with its body. A keyword inline is added before the function name to
make it inline. It is an optimization technique used by the compilers as it saves time in
switching between the functions otherwise. Member functions of a class are inline by
default even if the keyword inline is not used.

Syntax of Inline Function

inline return_type function_name ([argument list])

body of function

Inline function is suitable for small functions only. In case of large functions, it increases
the execution time slowing down the performance. Also, the code size increases
reasonably when a large function is called many times since the calling statement is
replaced by the body of function every time. So, in case of large functions, the compiler
ignores the programmers request to make a function inline even if the keyword inline is
used.

Following is an example, which makes use of inline function to return max of two
numbers −

#include <iostream>

inline int Max(int x, int y) {


return (x > y)? x : y;

void 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;

When the above code is compiled and executed, it produces the following result −

Max (20,10): 20

Max (0,200): 200

Max (100,1010): 1010

Q – 16 Explain default argument function with an example.

Ans. A default argument is a value provided in a function declaration that is automatically


assigned by the compiler if the caller of the function doesn’t provide a value for the
argument with a default value.

Following is a simple C++ example to demonstrate the use of default arguments. We


don’t have to write 3 sum functions, only one function works by using default values for
3rd and 4th arguments.

#include<iostream.h>
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}
void main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
}
Output:
25
50
80
Key Points:

 Default arguments are different from constant arguments as constant arguments


can’t be changed whereas default arguments can be overwritten if required.
 Default arguments are overwritten when calling function provides values for
them. For example, calling of function sum(10, 15, 25, 30) overwrites the value
of z and w to 25 and 30 respectively.
 During calling of function, arguments from calling function to called function are
copied from left to right. Therefore, sum(10, 15, 25) will assign 10, 15 and 25 to
x, y, and z. Therefore, the default value is used for w only.
 Once default value is used for an argument in function definition, all subsequent
arguments to it must have default value. It can also be stated as default
arguments are assigned from right to left. For example, the following function
definition is invalid as subsequent argument of default variable z is not default.

If you assign default value to an argument, the subsequent arguments must


have default values assigned to them, else you will get compilation error.

Q – 17 Explain function overloading with example.

Ans. The main advantage of function overloading is to improve the code readability and
allows code reusability. In the example, we have seen how we were able to have
more than one function for the same task(addition) with different parameters, this
allowed us to add two integer numbers as well as three integer numbers, if we wanted
we could have some more functions with same name and four or five arguments.

Imagine if we didn’t have function overloading, we either have the limitation to add only
two integers or we had to write different name functions for the same task addition, this
would reduce the code readability and reusability.

Example:

void display(); //function with no arguments

void display( int ); //function with one integer type arguments

void display( float ); //function with one floating point arguments

void display( int, float ); //function with one floating and one integer type arguments

Illustration of C++ function overloading

Example to illustrate the concept of C++ function overloading

// functionoverloading.cpp

#include <iostream>
void display ( ) //function with no arguments
{
int a = 3;
cout << a << endl;
}
void display (int a ) //function with one integer argument
{
cout << a << endl;
}
void display (double a ) //function with one floating argument
{
cout << a << endl;
}
void display(int a, float b) //function with one integer and one floating arguments
{
cout<< a << " , " << b << endl;
}
void main()
{
display(); //function call with no arguments
display(5); //function call with one integer argument
display(2.3); //function call with one floating argument
display(5,4.0); //function call with one integer and one floating arguments
} //end of program

Output
3
5
2.3
5,4
Explanation
In above program, when we call the function with no arguments the display()function
with no arguments is invoked and the result is 3. Similarly, when we pass one integer
type argument while calling the display(int a) function is invoked. Similarly, when we
pass integer and float value display(int a, float b) function is invoked. The advantage of
function overloading is that the number of names of functions is reduced.

So function overloading is achieved by varying following points:

 the number of parameters

 datatype of the parameters

 the order of the appearance of parameters

ISSUE DATE : 8/7/2020

SUBMISSION DATE : 15/7/2020

You might also like