Wa0003.
Wa0003.
Wa0003.
Statements
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.
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.
Data structures are designed such that they characterize the objects.
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.
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:
Overloading:
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.
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.
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.
Documentation Section
Main Function
/* 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.
o Declaring Structure
o Declaring Class
o Declaring Variable
Class declaration and all methods of that class are defined here.
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.
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.
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 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.
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;
}
}
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.
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
Constants
Constants are like a variable, except that their value never changes during execution
once defined.
Strings
i.e. Account::getBalance()
where Account is a class and getBalance() is a member function of the class Account.
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;
To assign the value "zara" to the first_name member of object emp, you would write
something as follows:
strcpy(emp.first_name, "zara");
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.
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.
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.
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
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;
}
Ans. It is a multi branch statement which can be used to select and execute one of the
available statements.
switch(value)
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.
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
}
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:
The function main can be defined with or without parameters, using any of the following
forms:
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.
Thus the above given examples are function definitions and the following are
declarations or shall we say, function prototypes :
Therefore, you can say that a function prototype has the following parts :
return type
argument list
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.
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:
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 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.
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>
void main() {
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
#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:
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( int, float ); //function with one floating and one integer type arguments
// 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.