BCA Sem II (OOPs) Unit II
BCA Sem II (OOPs) Unit II
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
C++ Token:
A C++ program is composed of tokens which are the smallest individual unit. Tokens can be one
of several things, including keywords, identifiers, constants, operators, or punctuation marks.
There are 6 types of tokens in c++:
• Keyword
• Identifiers
• Constants
• Strings
• Special symbols
• Operators
1. Keywords:
In C++, keywords are reserved words that have a specific meaning in the language and cannot be
used as identifiers. Keywords are an essential part of the C++ language and are used to perform
specific tasks or operations.
Some of the keywords in c++ are:
Class Auto static extern
register public private protected
try catch throw const
friend Inline new delete
2. Identifiers
In C++, an identifier is a name given to a variable, function, or another object in the code.
Identifiers are used to refer to these entities in the program, and they can consist of letters, digits,
and underscores. However, some rules must be followed when choosing an identifier:
• The first character must be a letter or an underscore.
• Identifiers cannot be the same as a keyword.
• Identifiers cannot contain any spaces or special characters except for the underscore.
• Identifiers are case-sensitive, meaning that a variable named "myVariable" is different
from a variable named "myvariable".
Valid: my_variable, student_name, balance_due
Invalid:
my variable (contains a space)
student# (contains a special character)
int (same as a keyword)
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
3. Constants
In C++, a constant is a value that cannot be changed during the execution of the program. Constants
often represent fixed values used frequently in the code, such as the value of pi or the maximum
size of an array.
To define a constant in C++, you use the const keyword followed by the data type and the constant's
name and then initialize it with a value. The value of a constant cannot be changed once it has been
defined. Here is an example:
const double PI = 3.14159;
4. String:
In C++, a string is a sequence of characters that represents text. Strings are commonly used in C++
programs to store and manipulate text data.To use strings in C++, you must include the <string>
header file at the beginning of your program.
5. Special symbols:
In C++, several special symbols are used for various purposes. The ampersand (&) is used to
represent the address of a variable, while the tilde (~) is used to represent the bitwise NOT operator.
Some of the most common special symbols include the asterisk (*), used as the multiplication and
pointer operators.
The pound sign (#) is used to represent the preprocessor directive, a special type of instruction
processed by the preprocessor before the code is compiled. The percent sign (%) is used as the
modulus operator, which is used to find the remainder when one number is divided by another.
The vertical bar (|) is used to represent the bitwise OR operator, while the caret (^) is used to
represent the bitwise XOR operator. The exclamation point (!) is used to represent the logical NOT
operator, which is used to negate a Boolean value.
In addition to these symbols, C++ also has a number of other special characters that are used for a
variety of purposes. For example, the backslash (/) is used to escape special characters, the double
quotes (") are used to enclose string literals, and the single quotes (') are used to enclose character
literals.
Overall, the special symbols in C++ are an important part of the language and are used in a variety
of different contexts to perform a wide range of operations.
6. Operators:
In C++, operators are special symbols that are used to perform operations on one or more operands.
An operand is a value on which an operator act’s. C++ has a wide range of operators, including
arithmetic operators, relational operators, logical operators, and others.
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
int main()
{
float R,H, volume;
const float PI=3.1417;
cout<<"Enter the value of R: ";
cin>>R;
cout<<"Enter the value of H: ";
cin>>H;
volume=PI*R*R*H;
cout<<"Volume of a Cylinder is = "<<volume;
}
Identifier:
It indicates the name of constant identifier to which the constant value is to be assigned. This name
cannot be used again in the program as variable name or function name etc.
Expression:
It indicates the constant value that is to be assigned to the identifier. It may be a constant value, a
string or an string or an arithmetic expression.
#define PI 3.141593
C++ allows us to allocate the memory of a variable or an array in run time. This is known as
dynamic memory allocation.
In C++, we need to deallocate the dynamically allocated memory manually after we have no use
for the variable.
We can allocate and then deallocate memory dynamically using the new and delete operators
respectively.
new operator-
Both the malloc() and new in C++ are used for the same purpose. They are used for allocating
memory at the runtime. But, malloc() and new have different syntax. The main difference between
the malloc() and new is that the new is an operator while malloc() is a standard library function
that is predefined in a stdlib header file.
The new is a memory allocation operator, which is used to allocate the memory at the runtime.
The memory initialized by the new operator is allocated in a heap. It returns the starting address
of the memory, which gets assigned to the variable. The functionality of the new operator in C++
is similar to the malloc() function, which was used in the C programming language. C++ is
compatible with the malloc() function also, but the new operator is mostly used because of its
advantages.
➢ type: It defines the datatype of the variable for which the memory is allocated by the new
operator.
➢ variable: It is the name of the variable that points to the memory.
➢ parameter_list: It is the list of values that are initialized to a variable.
The new operator does not use the sizeof() operator to allocate the memory. It also does not use
the resize as the new operator allocates sufficient memory for an object. It is a construct that calls
the constructor at the time of declaration to initialize an object.
As we know that the new operator allocates the memory in a heap; if the memory is not available
in a heap and the new operator tries to allocate the memory, then the exception is thrown. If our
code is not able to handle the exception, then the program will be terminated abnormally.
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
delete operator-
Once we no longer need to use a variable that we have declared dynamically, we can deallocate
the memory occupied by the variable.
For this, the delete operator is used. It returns the memory to the operating system. This is known
as memory deallocation.
delete pointer_variable;
// delete ptr;
It deallocates memory for one element
Similarly, we can delete the block of allocated memory space using the delete [] operator.
delete [ ] pointer_variable;
// delete [] ptr; It deallocate for an array
When a variable is declared as a reference, it becomes an alternative name for an existing variable.
A variable can be declared as a reference by putting ‘&’ in the declaration.
Also, we can define a reference variable as a type of variable that can act as a reference to another
variable. ‘&’ is used for signifying the address of a variable or any memory. Variables associated
with reference variables can be accessed either by its name or by the reference variable associated
with it.
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
return 0;
}
A reference variable is an alias, that is, another name for an already existing variable. Once a
reference is initialized with a variable, either the variable name or the reference name may be used
to refer to the variable.
References vs Pointers
References are often confused with pointers but three major differences between references and
pointers are −
You cannot have NULL references. You must always be able to assume that a reference is
connected to a legitimate piece of storage.
Once a reference is initialized to an object, it cannot be changed to refer to another object.
Pointers can be pointed to another object at any time.
A reference must be initialized when it is created. Pointers can be initialized at any time.
Integer
Character
Boolean
Floating Point
Double Floating Point
Valueless or Void
Wide Character
2. Derived Data Types: Derived data types that are derived from the primitive or built-in datatypes
are referred to as Derived Data Types. These can be of four types namely:
Function
Array
Pointer
Reference
3. Abstract or User-Defined Data Types: Abstract or User-Defined data types are defined by the
user itself. Like, defining a class in C++ or a structure. C++ provides the following user-defined
datatypes:
Class
Structure
Union
Enumeration
Typedef defined Datatype
❖ Boolean: Boolean data type is used for storing Boolean or logical values. A Boolean
variable can store either true or false. The keyword used for the Boolean data type is bool.
❖ Floating Point: Floating Point data type is used for storing single-precision floating-point
values or decimal values. The keyword used for the floating-point data type is float. Float
variables typically require 4 bytes of memory space.
❖ Double Floating Point: Double Floating Point data type is used for storing double-
precision floating-point values or decimal values. The keyword used for the double
floating-point data type is double. Double variables typically require 8 bytes of memory
space.
❖ void: Void means without any value. void data type represents a valueless entity. A void
data type is used for those function which does not return a value.
❖ Wide Character: Wide character data type is also a character data type but this data type
has a size greater than the normal 8-bit data type. Represented by wchar_t. It is generally
2 or 4 bytes long.
sizeof() operator: sizeof() operator is used to find the number of bytes occupied by a variable/data
type in computer memory.
Streams in C++:
In C++ stream refers to the stream of characters that are transferred between the program thread
and i/o.
Stream classes in C++ are used to input and output operations on files and io devices. These classes
have specific features and to handle input and output of the program.
The iostream.h library holds all the stream classes in the C++ programming language.
1. ios class − This class is the base class for all stream classes. The streams can be input or
output streams. This class defines members that are independent of how the templates of
the class are defined.
2. istream Class − The istream class handles the input stream in c++ programming language.
These input stream objects are used to read and interpret the input as a sequence of
characters. The cin handles the input.
3. ostream class − The ostream class handles the output stream in c++ programming
language. These output stream objects are used to write data as a sequence of characters on
the screen. cout and puts handle the out streams in c++ programming language.
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Manipulators in C++
The unformatted I/O statements that it is impossible to display output in a required user format or
input the values in the desired form. In certain situations, we may need to format the I/O as per
user requirements. For example :
To overcome the problems of unformatted I/O operations in C++, the concept of manipulators was
introduced.
The manipulators in C++ are special functions that can be used with insertion (<<) and extraction
(>>) operators to manipulate or format the data in the desired way. Certain manipulators are used
with << operator to display the output in a particular format, whereas certain manipulators are used
with >> operator to input the data in the desired form. The manipulators are used to set field widths,
set precision, inserting a new line, skipping white space etc.
To use most of the manipulators, we need to include the header file iomanip.h in the program.
Decision making is about deciding the order of execution of statements based on certain conditions
or repeat a group of statements until certain specified conditions are met. C++ handles decision-
making by supporting the following statements,
1. if statement
2. switch statement
case constant-expression :
statement(s);
break; //optional
Jump Statements
Jump statements are implemented to change the flow of the program when particular conditions
are satisfied. It is used within a program to end or continue a loop or to pause the execution of a
function. C++ has four jump statements: continue, break, return, and goto.
Continue:
Instead of terminating the loop, it performs the next iteration of the same loop but ignoring the
parts specified by the condition. Within the loop, it must be used in conjunction with a decision-
making statement. This statement can be used within a for, while, or do-while loop.
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
Break:
If the condition is met, the loop is terminated with the break command. When the condition is met,
the loop is broken and the remainder of the loop is skipped, unlike the continue statement. Break
statements are used in conjunction with decision-making statements such as if, if-else, or switch
statements in a for loop, which can be a for loop, while loop, or do-while loop. It causes the loop
to stop executing future iterations.
Return:
It removes control from the function. It is more powerful than a break. It is used to end the entire
function after the function has completed or after a condition has been met. Except for the void()
function, every function contains a return statement that returns some value. Although the void()
function can also have a return statement to conclude the function's execution.
Goto:
This statement enables us to jump directly to the section of the program that is being referenced.
Each goto statement is connected with a label that directs them to the section of the programme
for which they are named. Label statements can be written anywhere in the program; no before or
after goto statements are required. This statement makes understanding the flow of the program
difficult, hence it is avoided in program.
c++ is very strict with the type compatibility as compared to C language. for instance, c++
language defines int, short int, and long int as three different types, although each of these has size
of one byte. In C++ language the types of values must be the same for complete compatibility, or
a cast must be applied. These restrictions in c++ are necessary in order to support function
overloading where two functions with the same name are distinguished using the type of function
arguments
Another major difference is the way char constants are stored. in C programming, they are stored
as ints, and therefore is equivalent to sizeof(int) in c language, in c++ language, however, char is
not promoted to the size of int and therefore sizeof(‘y’) equals sizeof(char)
C++ is very strict with regard to type compatibility as compared to C programming. Type
compatibility is very close to implicit or automatic type conversion. The type compatibility is being
able to use two types being able to substitute one for the other without modification and together
without modification.
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
The type compatibility is categorized into following three types by the compiler:
1. Assignment compatibility
In assignment compatibility, if the one type of variable assigned to another type variable is
different It will results into loss of value of assigned variable if the size of the assigned variable is
large than the size of variable to which it is assigned.
For example
float f1=12.5;
int i1=f1;
This assigning of variable f1 float value to i1 int type will result in loss of decimal value of f1.
However, this type type compatibility will not show any type error but it might give a warning
“possible loss of data”.
2. Expression compatibility
Consider following example
int num=5/2;
cout<< num;
Here in the above example the result will be 2 because The actual result of 5/2 is 2.5 but because
of incompatibility there will be loss of decimal value
3. Parameter compatibility
Due to incompatibility when we pass the values from calling to called function in type of actual
parameter and formal parameters loss of data occurs.
For example
{ show(5.2);
}
Here output will be num=5 due to incompatibility in actual and formal parameter type.
Type Conversion
There are mainly two types of type conversion. The implicit and explicit.
Implicit type conversion
This is also known as automatic type conversion. This is done by the compiler without any external
trigger from the user. This is done when one expression has more than one datatype is present.
All datatypes are upgraded to the datatype of the large variable.
bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double
Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables
for each value.
To create an array, define the data type (like int) and specify the name of the array followed by
square brackets [].
Array in C is one of the most used data structures in C programming. It is a simple and fast way
of storing multiple values under a single name.
An array in C is a fixed-size collection of similar data items stored in contiguous memory locations.
It can be used to store the collection of primitive data types such as int, char, float, etc., and also
derived and user-defined data types such as pointers, structures, etc.
C Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an array
by specifying its name, the type of its elements, and the size of its dimensions. When we declare
an array in C, the compiler allocates the memory block of the specified size to the array name.
Types of Array in C :
There are two types of arrays based on the number of dimensions it has. They are as follows:
• One Dimensional Arrays (1D Array)
• Multidimensional Arrays
Syntax of 1D Array in C
array_name [size];
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
2. Multidimensional Array in C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the
popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more
dimensions than 3d arrays but they are avoided as they get very complex and occupy a large
amount of space.
A) Two-Dimensional Array in C
A Two-Dimensional array or 2D array in C is an array that has exactly
two dimensions. They can be visualized in the form of rows and
columns organized in a two-dimensional plane.
Syntax of 2D Array in C
array_name[size1] [size2];
B) Three-Dimensional Array in C
Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A
3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on
top of each other to create the third dimension.
Syntax of 3D Array in C
array_name [size1] [size2] [size3];
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II
Pointer
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an
address of a value.
The symbol of an address is represented by a pointer. In addition to creating and modifying
dynamic data structures, they allow programs to emulate call-by-reference.
Pointers are symbolic representations of addresses. They enable programs to simulate call-by-
reference as well as to create and manipulate dynamic data structures.
A pointer however, is a variable that stores the memory address as its value.
A pointer variable points to a data type (like int or string) of the same type, and is created with the
* operator. The address of the variable can be assigned to the pointer.
Pointer
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used
to group items of possibly different types into a single type.
The ‘struct’ keyword is used to create a structure. The general syntax to create a structure is as
shown below:
struct structureName{
member1;
member2;
.
.
memberN;
};
Struct Student
{ int roll; // Data Members
int age;
int marks;
void printDetails() // Member Function
{ cout<<"Roll = "<<roll<<"\n";
cout<<"Age = "<<age<<"\n";
cout<<"Marks = "<<marks;
}
};
RENAISSANCE UNIVERSITY, INDORE
BCA II SEM
Subject: Object Oriented Programming using C++
Unit II