Oosd notes
Oosd notes
KCS-054
UNIT 4
C++ INTRODUCTION
C++ is a MUST for students and working professionals to become a great Software
Engineer. I will list down some of the key advantages of learning C++:
• C++ is very close to hardware, so you get a chance to work at a low level
which gives you lot of control in terms of memory management, better
performance and finally a robust software development.
• C++ is one of the every green programming languages and loved by millions
of software developers. If you are a great C++ programmer then you will
never sit without work and more importantly you will get highly paid for
your work.
• C++ really teaches you the difference between compiler, linker and loader,
different data types, storage classes, variable types their scopes etc.
There are many C++ compilers available which you can use to compile and run
above mentioned program:
• Bloodshed Dev-C++
• Clang C++
• Mentor Graphics
• GNU CC source
• IBM C++
• Intel C++
• Oracle C++
• HP C++
As mentioned before, C++ is one of the most widely used programming languages.
It has it's presence in almost every area of software development. I'm going to list
few of them here:
The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is
needed.
The next line '// main() is where program execution begins.' is a single-line
comment available in C++. Single-line comments begin with // and stop at the end
of the line.
The line main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be
displayed on the screen.
You may like to store information of various data types like character, wide
character, integer, floating point, double floating point, boolean etc. Based on the
data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory.
C++ offers the programmer a rich assortment of built-in as well as user defined
data types. Following table lists down seven basic C++ data types −
Type Keyword
Boolean bool
Character char
Integer int
Several of the basic types can be modified using one or more of these type
modifiers −
• signed
• unsigned
• short
• long
The following table shows the variable type, how much memory it takes to store
the value in memory, and what is maximum and minimum value which can be
stored in such type of variables.
float 4bytes
double 8bytes
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because C++ is case-sensitive.
1 bool
2 char
3 int
4 float
5 double
A double-precision floating point value.
6 void
7 wchar_t
C++ also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Reference, Data
structures, and Classes.
A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type, and contains a list of one or
more variables of that type as follows −
type variable_list;
A scope is a region of the program and broadly speaking there are three places,
where variables can be declared −
We will learn what is a function and it's parameter in subsequent chapters. Here let
us explain what are local and global variables.
Identifiers in C++
The C++ identifier is a name used to identify a variable, function, class, module, or
any other user-defined item. An identifier starts with a letter A to Z or a to z or an
underscore (_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers.
C++ is a case-sensitive programming language. Thus, Manpower and manpower
are two different identifiers in C++.
When we assign a float value in a character value then compiler generates an error
in the same way if we try to assign any other value to the enumerated data types
the compiler generates an error. Enumerator types of values are also known as
enumerators. It is also assigned by zero the same as the array. It can also be used
with switch statements.
For example: If a gender variable is created with value male or female. If any
other value is assigned other than male or female then it is not appropriate. In this
situation, one can declare the enumerated type in which only male and female
values are assigned.
Syntax:
enum keyword is used to declare enumerated types after that enumerated type
name was written then under curly brackets possible values are defined. After
defining Enumerated type variables are created. It can be created in two types:
1. It can be declared during declaring enumerated types, just add the name of
the variable before the semicolon.or,
2. Beside this, we can create enumerated type variables as same as the normal
variables.
enumerated-type-name variable-name = value;
By default, the starting code value of the first element of enum is 0 (as in the case
of array) . But it can be changed explicitly.
For example:
first_enum e;
e=value3;
cout<<e;
Output:
11
#include <iostream.h>
using namespace std;
int main()
{
// Defining enum Gender
enum Gender { Male, Female };
switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
Operators in C++
Arithmetic Operators
There are following arithmetic operators supported by C++ language −
Assume variable A holds 10 and variable B holds 20, then −
Relational Operators
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then –
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then −
Operator Description Example
& Binary AND Operator copies a bit to the (A & B) will give 12 which is 0000
result if it exists in both operands. 1100
~ Binary Ones Complement Operator is (~A ) will give -61 which is 1100 0011
unary and has the effect of 'flipping' bits. in 2's complement form due to a signed
binary number.
Misc Operators
The following table lists some other operators that C++ supports.
1 sizeof
sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is
integer, and will return 4.
2 Condition ? X : Y
Conditional operator (?). If Condition is true then it returns value of X otherwise
returns value of Y.
3 ,
Comma operator causes a sequence of operations to be performed. The value of the
entire comma expression is the value of the last expression of the comma-separated list.
5 Cast
Casting operators convert one data type to another. For example, int(2.2000) would
return 2.
6 &
Pointer operator & returns the address of a variable. For example &a; will give actual
address of the variable.
7 *
Pointer operator * is pointer to a variable. For example *var; will pointer to a variable
var.
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
C++ programming language provides following types of decision making
statements.
Sr.No Statement & Description
1 if statement
An ‘if’ statement consists of a boolean expression followed by one or more statements.
2 if...else statement
An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when
the boolean expression is false.
3 switch statement
A ‘switch’ statement allows a variable to be tested for equality against a list of values.
4 nested if statements
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
5 nested switch statements
You can use one ‘switch’ statement inside another ‘switch’ statement(s).
There may be a situation, when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times
C++ programming language provides the following type of loops to handle looping
requirements.
Sr.No Loop Type & Description
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.
2 for loop
Execute a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 do...while loop
Like a ‘while’ statement, except that it tests the condition at the end of the loop body.
4 nested loops
You can use one or more loop inside any another ‘while’, ‘for’ or ‘do..while’ loop.
C++ supports the following control statements.
Sr.No Control Statement & Description
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.
3 goto statement
Transfers control to the labeled statement. Though it is not advised to use goto
statement in your program.
A type cast is basically a conversion from one type to another. There are two types
of type conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
• Done by the compiler on its own, without any external trigger from
the user.
• Generally takes place when in an expression more than one data type
is present. In such condition type conversion (type promotion) takes
place to avoid lose of data.
• All the data types of the variables are upgraded to the data type of the
variable with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
• It is possible for implicit conversions to lose information, signs can be
lost (when signed is implicitly converted to unsigned), and overflow
can occur (when long long is implicitly converted to float).
Example of Explicit type conversion:
#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
return 0;
}
Output:
x = 107
y=a
z = 108
Explicit Type Conversion: This process is also called type casting and it is user-
defined. Here the user can typecast the result to make it of a particular data type.
In C++, it can be done by two ways:
• Converting by assignment: This is done by explicitly defining the required
type in front of the expression in parenthesis. This can be also considered as
forceful casting.
•
Syntax:
(type) expression
where type indicates the data type to which the final result is converted.
#include <iostream>
using namespace std;
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
cout << "Sum = " << sum;
return 0;
}
Output:
Sum = 2
#include <iostream>
using namespace std;
int main()
{
float f = 3.5;
cout << b;
}
Output:
3
Functions in C++
A function is a set of statements that take inputs, do some specific computation and
produces output.
The idea is to put some commonly or repeatedly done task together and make a function
so that instead of writing the same code again and again for different inputs, we can call
the function.
The general form of a function is:
return_type function_name([ arg1_type arg1_name, ... ])
{
code //function to performed
}
Pass/call by Reference :Both actual and formal parameters refer to same locations,
so any changes made inside the function are actually reflected in actual parameters
of caller.
Parameters are always passed by value in C++. For example in the below code,
value of x is not modified using the function fun().
Call by value:
#include <iostream>
using namespace std;
void fun(int x) {
x = 30; }
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
Output:
x = 20
Call by reference:
#include <iostream>
using namespace std;
void fun(int *ptr)
{
*ptr = 30;
}
int main() {
int x = 20;
fun(&x);
cout << "x = " << x;
return 0;
}
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.
#include <iostream>
using namespace std;
inline int cube(int s)
{
return s*s*s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";
return 0;
}
Output: The cube of 3 is: 27
We can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. We cannot
overload function declarations that differ only by return type.
#include <iostream>
using namespace std;
class printData {
public:
void print(int i)
{
cout << "Printing int: " << i << endl;
}
void print(double f)
{
cout << "Printing float: " << f << endl;
}
void print(char* c)
{
cout << "Printing character: " << c << endl;
}
};
int main(void) {
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
return 0;
}
Output:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
#include<iostream>
using namespace std;
// A function with default arguments, it can be called with
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
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 class A is a friend of B, then B doesn’t become a
friend of A automatically.
3) Friendship is not inherited
4) The concept of friends is not there in Java.
#include <iostream>
class A {
private:
int a;
public:
A() { a = 0; }
friend class B; // Friend Class
};
class B {
private:
int b;
public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
};
int main()
{
A a;
B b;
b.showA(a);
return 0;
}
Output:
A::a=0
Virtual Function in C++:
A virtual function is 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.
• Virtual functions ensure that the correct function is called for an object,
regardless of the type of reference (or pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time.
#include <iostream>
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;
}
};
int main()
{
base* bptr;
derived d;
bptr = &d;
Output: