CPP Unit 2
CPP Unit 2
2.1 Tokens, Expressions and Control Structures Tokens, keywords, identifiers, constants and
symbolic constants, data types and its classifications, type casting,
2.2 Variables: introduction, declaration, dynamic initialization,reference.
2.3 Operators : introduction, scope resolution operator, type cast operator, memory
management operators, operator precedence
2.4 Expressions: introduction, types, special assignment Expressions
2.5 Access Specifiers: introduction, why there is need of access specifiers, types of access
specifiers.
2.6 Control structures : introduction, types of control structures like sequence structure,
selection structure, loop structure, example of all the types of structures like if-else, while,
do- while, for, switch with its syntax and usage.
2.7 Classes and Objects Classes: Introduction, use of classes in OOP, syntax to declare class,
local classes. Objects: introduction, memory allocation for objects, static data members,
array of objects, objects as function arguments, returning objects.
2.8 Constructors and Destructors Constructors : introduction, syntax, concept of memory
allocation using constructors, types of constructors, constructors with default arguments,
dynamic initialization of objects, dynamic constructors Destructors: introduction, syntax,
concept of memory deallocation using destructors, example.
***************************************************************************
Token
➢ The smallest individual units in a C++ program are known as tokens that is
meaningful to the compiler.
➢ C++ has the following tokens.
i. Keywords
ii. Identifiers
iii. Constants/Symbolic Constants
iv. Strings – Group of Characters
v. Operators
Keywords
➢ It is reserved identifiers and cannot be used as names for the program
variables or other user defined program elements.
Identifiers
➢ A symbolic name is generally known as an identifier.
➢ Valid identifiers are a sequence of one or more letters, digits, or underscore
characters (_).
➢ Neither spaces nor punctuation marks or symbols can be part of an identifier.
➢ Only letters, digits and single underscore characters are valid.
➢ The rules for the formation of identifier - •An identifier may include of
alphabets, digits and/or underscores.
• It must not start with a digit and should not be a reserved word• C++
is case sensitive, i.e, upper case and lower-case letters are considered
totally different from each other.
• It may be noted that TOTAL and total are two different identifier
names.
Symbolic Constants
➢ Constants can be defined as the expression with fixed values.
➢ There are two ways of creating symbolic constants in c++.
Type Casting
➢ Type casting refers to the conversion of one data type to another in a
program.
➢ Typecasting can be done in two ways: automatically by the compiler and
manually by the programmer or user.
➢ Type Casting is also known as Type Conversion.
➢ There are Two types of type casting/Conversion
1. Implicit Type Casting or Implicit Type Conversion
2. Explicit Type Casting or Explicit Type Conversion
Variables
➢ We might want to give a value a name so we can refer to it later. We do this
using variable. A variable is a named location in memory.
➢ For example, say we wanted to use the value 4 + 2 multiple times. We might
call it x and use it as follows:
# include < iostream >
using namespace std ;
int main () {
int x;
x = 4 + 2;
cout << x / 3 << ’ ’ << x * 2;
return 0;}
➢ The name of a variable is an identifier token. Identifiers may contain
numbers, letters, and underscores (_), and may not start with a number.
➢ Line 4 is the declaration of the variable x. We must tell the compiler what
type x will be so that it knows how much memory to reserve for it and what
kinds of operations may be performed on it.
➢ Line 5 is the initialization of x, where we specify an initial value for it. This
introduces a new operator: =, the assignment operator. We can also change
the value of x later in the code using this operator.
➢ We could replace lines 4 and 5 with a single statement that does both
declaration and initialization: int x = 4 + 2;
➢ This form of declaration/initialization is cleaner, so it is to be preferred.
Declaration Of Variable
➢ In ANSIC C all the variable which is to be used in programs must be
declared at the beginning of the program. But in C++ we can declare the
variables any whose in the program where it requires.
➢ This makes the program much easier to write and reduces the errors that may
be caused by having to scan back & forth It also makes the program easier
to understand because the variables are declared in the context of their use.
➢ Example:
int main(){
float x, sum=0;
for(int i=1;i<5;i++){
cin>>x;
sum=sum+x
}
float average;
average=sum/x; cout<<average;
return 0;
}
Reference Variable
➢ C++ interfaces a new kind of variable known as the reference variable,
used for accessing & modifying value.
➢ A references variable provides an alias. (alternative name) for a previously
defined variable.
➢ For example, if we make the variable sum a reference to the variable total,
then sum and total can be used interchangeably to represent the variable.
Relational Operators
Logical Operators
1. Logical AND (&&) :
Example:- a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole
expression is true only if both expressions are true i.e., if a is greater than b and
x is equal to 10.
2. Logical OR (||) :
Example : a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are
true. It evaluates to true if a is less than either m or n and when a is less than
both m and n.
3. Logical NOT (!) :
For example : ! (x >= y)
The NOT expression evaluates to true only if the
value of x is neither greater than or equal to y.
Truth Table:
Example : if(age > 55 && salary <
1000)
if(number < 0 || number > 100)
Assignment Operators
Example : x + = 1 is same as x = x + 1 The commonly used shorthand
assignment operators are as follows:
Bitwise Operators
➢ ^ (XOR)
➢ | (OR)
➢ & (AND)
➢ ~ (complement)
➢ << (shift left, insertion to stream)
➢ >> (shift right, extraction from stream)
Conditional operator:
➢ This is the only ternary operator in C. The operator pair ?: is used to
construct conditional expression.
➢ Syntax: exp1 ? exp2 : exp3
Ex:
a = 10;
b = 15;
X = (a>b) ? a : b;
Here X will be assigned 15 i.e. the value of b.
Its same as
if (a > b)
x = a;
else
x = b;
Operator Precedence
#include<math.h>
Access specifiers
➢ In C++ Access specifies are also called as visibility mode. They are as
follows: Public, Private, and Protected .
➢ Public:- When access specifier is public i.e. base class is publicly inherited
by derived class all public member
of base class become public
members of derived class and all
protected members become
protected in derived class.
➢ Private: - All public and protected
members of base class become
private members of derived class.
➢ Protected: - In this all public and
protected members of base class
become protected of derived class
➢ If no access specifier is specified then it is treated by default as private
➢ The default access specifier of structure is public where as that of a class is
“private”
Control Structures
➢ Control structures are portions of program code that contain statements
within them and, depending on the circumstances, execute these statements
in a certain way.
➢ There are typically two kinds: conditionals and loops.
1. Conditional Statement-
• If (Sequence statement)
• if-else (Sequence statement)
• else if (Sequence statement)
14 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104
If conditional statement
➢ The if conditional has the form:
if(condition)
{
statement1 statement2 …
}
➢ The condition is some expression whose value is being tested. If the
condition resolves to a value of true, then the statements are executed before
the program continues on. Otherwise, the statements are
ignored. If there is only one statement, the curly braces may be omitted,
giving the form:
if(condition)
Statement;
if(condition) statementA1
else
statementB1
while statement
➢ The while loop has a form similar to the if conditional:
while(condition){
statement1
statement2
….……. }
➢ As long as condition holds, the block of statements will be repeatedly
executed. If there is only one statement, the curly braces may be omitted.
Here is an example:
#include <iostream>
using namespace std;
int main() {
int x = 0; 6
while(x < 10)
x = x + 1;
cout << "x is " << x << " \n ";
return 0; }
➢ This program will print x is 10.
Do while statement
➢ The do-while loop is a variation that guarantees the block of statements will
be executed at least once:
do
{
statement1 statement2 …
17 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104
}
while(condition);
➢ The block of statements is executed and then, if the condition holds, the
program returns to the top of the block.
➢ Curly braces are always required. Also note the semicolon after the while
condition
For statement
➢ The for loop works like the while loop but with some change in
syntax: for(initialization; condition; increment){
statement1
statement2 …
}
➢ The for loop is designed to allow a counter variable that is initialized at the
beginning of the loop and incremented (or decremented) on each iteration of
the loop. Curly braces may be omitted if there is only one statement. Here is
an example:
#include <iostream>
using namespace std;
int main() {
for(int x = 0; x < 10; x++)
cout << x << " \n " ;
return 0; }
➢ This program will print out the values 0 through 9, each on its own line
Class
➢ Class is a group of objects that share common properties &relationships
➢ Class is a collection of objects.
Or
A class is a blueprint of the object.
➢ Generally a class specification has two parts:-
Class declaration
Class function definition
➢ Syntax:-
class class-name{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};
➢ Example
class item {
private:
char name [30];
float cost;
public:
void getldata (char a[] ,float b);
void putdata (void);
};
Objects
➢ Definition : Objects are basic run time entities in an object oriented system.
➢ They may represent a person, a place, a bank account, a table of data or any
item that the program has to handle.
➢ An object is the instance of the class.
➢ Object can be declared same as the variable declaration.
Declaring objects
➢ The declaration of object is same as declaration of variables of basic data
types.
➢ Defining objects of class data type is known as class instantiation.
➢ Memory is allocated only when objects are created.
➢ Syntax: class_name variable_name;
➢ Ex: student s;
student s1,s2, *s3; // declaration of object or class type variablesWhere
s1, s2, s3 are three objects of class student .
*s3 is a pointer to class student.
• A static member function can have access to only other static members
declared in the same class.
• A static member function can be called using the class name:
Class_name::function_name;
• Syntax:
1)Inside the class:
static datatype variblename;
Eg:static int a;
2)outside the class:
return_type classname::variablename;
eg-int student::a;
int student::a=5;
➢ Use of static data member:
• Static data member (variable) is used to maintain values common to the
entire class.
• Only one copy of static member is created for the entire class and is
shared by all the objects of that class.
• Its lifetime is the entire program.
Array of Object
➢ Array of a Variables that are of type class are called array of object.
➢ The arrays can be used as member variables in a class.
➢ An array is a collection of same data type or group of data item that stored in
a common name.
➢ Syntax: classname objectname[size];
➢ Example: 1.student s[10];
employee E[3];
(three objects E[0], E[1], E[2] are created)
Returning an Object
➢ An object is an instance of a class. Memory is only allocated when an object
is created and not when a class is defined.
➢ An object can be returned by a function using the return keyword.
➢ A function can also return objects either by value or by reference.
➢ When an object is returned by value from a function, a temporary object is
created within the function, which holds the return value.
➢ This value is further assigned to another object in the calling function.
Constructor in C++
➢ Constructor is a member function of the class.
➢ It is called special member function because the name of the constructor
is same as name of the class.
➢ Constructor is used to construct the values for the data member of the
class automatically when the object of class is created.
➢ Like other member function there is no need to call constructor explicitly.
It is invoked automatically each time the object of its class is created.
➢ Every class having at least one constructor defined in it. If you do not
define any constructor in the class then compiler will automatically create
a constructor inside the class and assigns default value (0) to the data
member of the class.
Characteristics of constructor
➢ It is called automatically when object of its class is created.
➢ It does not return any value.
➢ It must be declared inside public section of the class.
➢ It can have default arguments.
➢ Inheritance of constructor is not possible.
➢ It can not virtual.
➢ Constructor is invoked whenever an object of its associated class is
created.
➢ Disadvantage of default constructor –
➢ Each time an object is created it will assign same default values to the
data members of the class.
➢ It is not possible to assign different values to the data members for the
different object of the class using default constructor.
Types of constructor
➢ Default constructor
➢ Parameterised constructor
➢ Copy constructor
➢ Dynamic constructor
Default constructor
➢ A constructor that accepts no parameters is called the default constructor.
➢ If default constructor is not defined in program then the compiler supplies
a default constructor
➢ Constructor declaration wit Exclass student {
int rollno;
char name[20];
public: student();
};
➢ Constructor definition--
student::student(){ rollno=0; name=”Priya”; }
➢ Constructor calling–
void main(){ student s; .... }
➢ Constructor can be defined inside class as shown below:class Rectangle {
int Height, Width;
public: Rectangle(){
Height = Width = 1;
}
};
25 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104
Parameterized Constructor
➢ It is possible to pass arguments to constructor functions. These arguments
help to initialize an object when it is created.
➢ To create parameterized constructor, simply add parameters to the
constructor function and when you define the constructors body use
parameters to initialize objects.
➢ The constructor that can take arguments are called parameterized
constructor.
➢ Parameterized Constructor Declaration With Exclass student{
int rollno;
char name[20];
public:
student(int rn, char nm[20]);
};
➢ Parameterized Constructor definition--
student::student(int rn, char nm[20]){
rollno=rn; strcpy(name,nm); }
➢ Constructor calling–
void main(){
student s(1,”abc”), s2(2,”aa”);
........ }
Copy constructor
➢ The process of copying one object data in to another object is called as
Copy Constructor.
➢ A copy constructor is a constructor which is used to initialize the current
values with another object value.
➢ Copy constructor is used to create another Copy or Xerox of one object.
➢ A copy constructor takes a reference to an object of the same class as
itself as an argument.
Overloaded/Multiple Constructor
➢ Multiple constructors is a category of constructor in which a class can
have more than one constructor. This is also known as constructor
overloading.
➢ All constructors are defined with the same name as the class name they
belong to.
➢ Each of the constructors contains different number of arguments or
different data type of arguments.
➢ Depending upon the number of arguments and their data type, the
compiler executes appropriate constructor.
Dynamic Object
➢ An object that is created at run time is called as a dynamic object.
➢ The construction & destruction of dynamic object is explicitly done by
the programmer using new and delete operators.
➢ A dynamic object can be created using new operator.
ptr = new class_name;
➢ Where the variable ptr is a pointer object of the same class the new
operator returns the object created and it is stored in the pointer ptr.
delete object syntax is : delete ptr;
Dynamic Constructor
➢ When allocation of memory is done dynamically using dynamic memory
allocator new in a constructor, it is known as dynamic constructor.
➢ This allows us to initialize objects dynamically.
➢ The term dynamic constructor is used when memory allocation is done
dynamically inside a constructor using the keyword new.
➢ The dynamic constructor will not create any memory for the object.
However, it creates a memory block that the objects could access.
Destructors in C++
➢ When ever constructor is executed object is defined and memory is
allocated.
➢ Now to release (or) delete this memory we use destructor.
➢ Destructor is also one special member function, which is used to delete
the memory created by the constructor.
➢ Constuctor constructs the memory (or) Constructor constructs the object
data.
➢ Destructor is used to delete this memory created by constructor.
➢ Using destructors is a good practice because it automatically release the
memory occupied by the constructor.
Characteristics of Destructors
➢ Destructor name should be similar to class name and preceded by 'tilde'
operator(~).
➢ Ex: class sample {
sample() { ----------- } //constructor
~sample() { ---------- } //Destructor };
➢ Destructor should be declared in public section.
➢ They are invoked automatically when object goes out of scope.
➢ Destructor doesn't have any arguments/default arguments, so overloading
is not possible.
➢ Destructor never returns a value, it makes a implicit call new and delete
operator.
➢ Destructor never called with object followed by dot(.) operator.
➢ Destructor never participate in inheritance.
********************************************************