0% found this document useful (0 votes)
14 views37 pages

OOPS Unit 1 & 2 Notes

This document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. It explains the structure of a C++ program, the importance of OOP in organizing data and functions, and the classification of C++ tokens such as keywords, identifiers, constants, and operators. The document emphasizes the features and advantages of using OOP in programming.

Uploaded by

ishakkumar783
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views37 pages

OOPS Unit 1 & 2 Notes

This document provides an overview of Object-Oriented Programming (OOP) concepts in C++, including classes, objects, encapsulation, abstraction, polymorphism, inheritance, dynamic binding, and message passing. It explains the structure of a C++ program, the importance of OOP in organizing data and functions, and the classification of C++ tokens such as keywords, identifiers, constants, and operators. The document emphasizes the features and advantages of using OOP in programming.

Uploaded by

ishakkumar783
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT 1

1. Basic Concepts of OOPs in C++


TABLE OF CONTENT:
1. Introduction
2. Class
3. Objects
4. Encapsulation
5. Abstraction
6. Polymorphism
7. Inheritance
8. Dynamic Binding
9. Message Passing

Object-oriented programming – As the name suggests uses objects in


programming. Object-oriented programming aims to implement real-world entities like
inheritance, hiding, polymorphism, etc in programming.
The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
Characteristics of an Object Oriented Programming language

Class:
The building block of C++ that leads to Object-Oriented programming is a Class. It is a
user-defined data type, which holds its own data members and member functions, which
can be accessed and used by creating an instance of that class. A class is like a blueprint
for an object.

● A Class is a user-defined data-type which has data members and member functions.
● Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
define the properties and behaviour of the objects in a Class.
● In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can apply brakes, increase speed etc.
We can say that a Class in C++ is a blue-print representing a group of objects which
shares some common properties and behaviors.

Object:
An Object is an identifiable entity with some characteristics and behaviour. An
Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.
class person
{
char name[20];
int id;
public:
void getdetails(){}
};

int main()
{
person p1; // p1 is a object
}

Object take up space in memory and have an associated address like a record in pascal or
structure or union in C.
When a program is executed the objects interact by sending messages to one another.
Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of
message accepted and type of response returned by the objects.

Encapsulation:
In normal terms, Encapsulation is defined as wrapping up of data and information
under a single unit. In Object-Oriented Programming, Encapsulation is defined as binding
together the data and the functions that manipulate them.
Encapsulation also leads to data abstraction or hiding. As using encapsulation also hides
the data. In the above example, the data of any of the section like sales, finance or
accounts are hidden from any other section.

Abstraction:
Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.

● Abstraction using Classes: We can implement Abstraction in C++ using classes.


The class helps us to group data members and member functions using available
access specifiers. A Class can decide which data member will be visible to the
outside world and which is not.
● Abstraction in Header files: One more type of abstraction in C++ can be header
files. For example, consider the pow() method present in math.h header file.
Whenever we need to calculate the power of a number, we simply call the function
pow() present in the math.h header file and pass the numbers as arguments without
knowing the underlying algorithm according to which the function is actually
calculating the power of numbers.

Polymorphism:
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than one form.
A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. So the same person posses different behaviour in
different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour
depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
● Operator Overloading: The process of making an operator to exhibit different
behaviours in different instances is known as operator overloading.
● Function Overloading: Function overloading is using a single function name to
perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, sometimes there are
2 integers; sometimes there are 3 integers. We can write the Addition Method with the
same name having different parameters; the concerned method will be called according to
parameters.

Inheritance:
The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.

● Sub Class: The class that inherits properties from another class is called Sub class
or Derived Class.
● Super Class:The class whose properties are inherited by sub class is called Base
Class or Super class.
● Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

Dynamic Binding:
In dynamic binding, the code to be executed in response to function call is decided
at runtime. C++ has virtual functions to support this.

Message Passing:
Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and
therefore will invoke a function in the receiving object that generates the desired results.
Message passing involves specifying the name of the object, the name of the function and
the information to be sent.

2.Structure of C++ program


Include Files
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
(i) Link Section
(ii) Definition Section
3. Global Declaration Section
Class declaration or definition
1. Class name or name of class
2. Data Members
3. Member Functions
4. Access Specifiers
Member function definition
1. Defining function inside class declaration
2. Defining function outside class declaration
Main C++ program function called main ( )
1. Beginning of the program: Left brace {
(i) Object declaration part;
(ii) Accessing member functions (using dot operator);
2. End of the main program: Right brace}

Include files

1. Documentation Section
In Documentation section we give the Heading and Comments. Comment
statement is the non-executable statement. Comment can be given in two ways:
(i) Single Line Comment: Comment can be given in single line by using "II".
The general syntax is: II Single Text line
(ii) Multiple Line Comment: Comment can be given in multiple lines starting by
using "/*" and end with "*/".
2. Preprocessor Directives
Pre-compiler statements are divided into two parts.
(i) Link Section:
In the Link Section, we can link the compiler function like cout<<, cin>>,
sqrt ( ), fmod ( ), sleep ( ), clrscr ( ), exitO, strcatO etc.
ii) Definition Section:
The second section is the Definition section by using which we can define a
variable with its value. For this purpose define statement is used.
3. Global Declaration Section
Declare some variables before starting of the main program or outside
the main program. These variables are globally declared and used by the main
function or sub function
Class declaration or definition

A class is an organization of data and functions which operate on them. Data types are
called data members and the functions are called member functions. The combination of
data members and member functions constitute a data object or simply an object.

The general syntax or general form of the class declaration is as follows:

class <name of class>


{
private:
data members;
member functions O;
public:
data members;
member functions O;
protected:
data members;
member functions O;
};
mainO
{
<name of class> obj1;
obj1.member function O;
obj1.member functionO;
getchO;
}

1. Class name or name of class


It is mainly the name given to a particular class. It serves as a name specifier for
the class, using which we can create objects. The class is specified by keyword
"class".
For example: class Circle
Here Circle is the class name.
2. Data Members
These are the data-type properties that describe the characteristics of a class. We
can declare any number of data members of any type in a class. We can say that the
variables in C and data members in C++.
For example: float area;
3. Member Functions
These are the various operations that can be performed to data members of that
class..
For example: void read(); void display();
4. Access Specifiers
Access Specifiers are used to identify access rights for the data members and
member functions of the class.
There are three main types of access Specifiers in C++ programming language:
1. Private: A private member within a class denotes that only members of the
same class have accessibility. The private member is not accessible
from outside the class.
2. Public: Public members are accessible from outside the class.
3. Protected: A protected access specifier is a stage between private and public
access. If member functions defined in a class are protected, they
cannot be accessed from outside the class but can be accessed from
the derived class (inheritance).

Member function definition

1. Defining member function inside of the class definition (member function


definition with declaration)
Consider the following syntax
class class_name
{
private:
data_type variable_names;
public:
return_type function_name(parameter_list)
{
function_body;
}
};
Example : Definition of a member function inside a class
class book
{
char title[30];
float price;
public:
void getdata(char [],float); II declaration
void putdata()//definition inside the class
{
cout<<"\nTitle of Book: "<<title;
cout<<"\nPrice of Book: "<<price;
};

2. Defining member function outside of the class definition


Defining a member function outside a class requires the function declaration
(function prototype) to be provided inside the class definition.
The definition of member function outside the class differs from normal function
definition, as the function name in the function header is preceded by the class name
and the scope resolution operator (: :).
The scope resolution operator informs the compiler what class the member
belongs to.
class class_name
{
private:
data_type variable_names;
public:
return_type function_name(parameter_list);
};
The syntax for defining a member function outside the class is

Return_type class_name :: function_name (parameter_list)


{
// body of the member function
}

Main C++ program function called main ( )

main function is where a program starts execution. Main () program is the C++
program's main structure in which we process some statements. The main function
usually organizes at a high level the functionality of the rest of the program.
The general syntax is: main ( )
1. Beginning of the Main Program: Left Brace {
(The beginning of the main program can be done by using left curly brace "{").
(i) Object declaration part
We can declare objects of class inside the main program or outside the main
program.
For example: b1 is the object of the class book. We can create any number of
objects of a given class.

(ii) Accessing member functions (using dot operator)


The member function define in the class are access by using dot (.)
operator. Suppose we have two member functions void getdata() and void
putdata(). We have to access these member functions in the main program.
syntax:
Obj1. Member function ();
For example:
b1.getdata (“balagurusamy”,300);
Here b1 is object and getdata() is the member function of class book.
2. Ending of The Main Program: Right Brace}
(The right curly brace "}" is used to end the main program).
main ( )
{
book b1;
b1.getdata(“balagurusamy”,300);
b1.putdataO;
getch( );
}

3. Object-Oriented Programming Paradigm

● The major motivating factor in the invention of object-oriented approch is to


remove some of the flaws encountered in the procedural approch.
● 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.
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.

UNIT -2
C++ Tokens
A token is the smallest element of a program that is meaningful to the compiler.
Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators

1. Keyword:
Keywords are those words whose meaning is already defined by Compiler.
These keywords cannot be used as an identifier. Note that keywords are the collection
of reserved words and predefined identifiers..Every Keyword exists in lower case

C language supports 32 keywords which are given below:


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

While in C++ there are 31 additional keywords other than C Keywords they
are:
asm bool catch class
const_cast delete dynamic_cast explicit
export false friend inline
mutable namespace new operator
private protected public reinterpret_cast
static_cast template this throw
true try typeid typename
using virtual wchar_t

2. Identifiers:
Identifiers are used as the general terminology for naming of variables,
functions and arrays. These are user defined names consisting of arbitrarily
long sequence of letters and digits with either a letter or the underscore(_) as a
first character. Identifier names must differ in spelling and case from any
keywords. You cannot use keywords as identifiers; they are reserved for
special use.

There are certain rules that should be followed while naming c


identifiers:
● They must begin with a letter or underscore(_).
● They must consist of only letters, digits, or underscore. No other special
character is allowed.
● It should not be a keyword.
● It must not contain white space.
● It should be up to 31 characters long as only first 31 characters are
significant.
Some examples of c identifiers:

NAME REMARK

_A9 Valid
Invalid as it contains special character other than the
Temp.var underscore
void Invalid as it is a keyword

1. Constants:
Constants are also like normal variables. But, only difference is, their values
can not be modified by the program once they are defined. Constants refer to
fixed values. They are also called as literals.

Constants may belong to any of the data type.Syntax:


const data_type variable_name; (or) const data_type *variable_name;

Types of Constants:
● Integer constants – Example: 0, 1, 1218, 12482
● Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
● Octal & Hexadecimal constants – Example: octal: (013 )8 =
(11)10, Hexadecimal: (013)16 = (19)10
● Character constants -Example: ‘a’, ‘A’, ‘z’
● String constants -Example: “GeeksforGeeks”

2. Strings:
Strings are nothing but an array of characters ended with a null character (‘\
0’).This null character indicates the end of the string. Strings are always enclosed
in double quotes. Whereas, a character is enclosed in single quotes in C and C++.

Declarations for String:


● char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘\
0’};
● char string[20] = “geeksforgeeks”;
● char string [] = “geeksforgeeks”;

1. Special Symbols:
The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = #
● Brackets[]: Opening and closing brackets are used as array element
reference. These indicate single and multidimensional subscripts.
● Parentheses(): These special symbols are used to indicate function calls
and function parameters.
● Braces{}: These opening and ending curly braces marks the start and end
of a block of code containing more than one executable statement.
● comma (, ): It is used to separate more than one statements like for
separating parameters in function calls.
● semi colon : It is an operator that essentially invokes something called an
initialization list.
● asterick (*): It is used to create pointer variable.
● assignment operator: It is used to assign values.
● pre processor(#): The preprocessor is a macro processor that is used
automatically by the compiler to transform your program before actual
compilation.

2. Operators:
Operators are symbols that triggers an action when applied to C variables and
other objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators
can be classified as follows:
● Unary Operators: Those operators that require only single operand to act
upon are known as unary operators.For Example increment and decrement
operators
● Binary Operators: Those operators that require two operands to act upon
are called binary operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators: These operators requires three operands to act upon.
For Example Conditional operator(?:).
For more information about operators
2. Control Structure in C++
A control structure is a block of programming that analyzes variables
and chooses a direction in which to go based on given parameters. The term
flow control details the direction the program takes

Types of Control Structure

1.Branching
2.Looping

Branching statement

⮚ if statement
⮚ if..else statements
⮚ if-else-if ladder
⮚ nested if statements
⮚ switch statements

If Statement:

The if statement selects and executes the statement(s) based on a given


condition. If the condition evaluates to True then a given set of statement(s) is
executed.
If the condition evaluates to False, then the given set of statements is
skipped and the program control passes to the statement following the if statement.

Syntax

if (condition)
{
statement 1;
statement 2;
statement 3;
}

Example

if (mark>40)

Cout<<”PASS”;

}
If-else Statement:

The if-else statement comprises two parts, namely, if and else.


The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false he else statement ll be execute . We can use
the else statement with if statement to execute a block of code when the condition
is false
Syntax

if (condition)

// Executes this block if

// condition is true

else

// Executes this block if

// condition is false

Example

if(x>y)
cout<<”X is greater”;
else
cout<<”y is greater”;

Nested if-else Statement:

A nested if-else statement contains one or more if-else statements. Nested if


statements means an if statement inside another if statement.
Syntax

if (condition1)

// Executes when
condition1 is true

if (condition2)

// Executes when
condition2 is true

Else{}

Example

if (a>b)
{
if (a>c)
cout<<”a is largest”;
}
else //nested if-else
statement within else
{
if (b>c)
cout<<”b is largest”;
else
cout<<”c is largest”;
}

if-else-if ladder
The if-else-if staircase, has an if-else statement within the outermost else
statement. The inner else statement can further have other if-else statements. As
soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed
Syntax

if (condition)

statement;

else if (condition)

statement;

else

statement;

Example
char ch;
cout<<"Enter an alphabet:";
cin>>ch;
if( (ch>='A') && (ch<='Z'))
cout <<"The alphabet is in upper
case";
else if ( (ch>=' a') && (ch<=' z' ) )
cout<<"The alphabet is in lower
case";
else
cout<<"It is not an alphabet";
return 0;
}
The switch Statement:
The switch statement selects a set of statements from the available sets of
statements. The switch statement tests the value of an expression in a sequence and
compares it with the list of integers or character constants.

Syntax
switch(expression)
{
case <constant1>: statement1;
[break;]
case <constant2>: statement2;
[break;]
case <constant3>: statement3;
[default: statement4;]
[break;]
}
Statement5;
Example
cin>>x;
int x;
switch(x)
{
case l: cout<<"Option1 is
selected";
break;
case 2: cout<<"Option2 is
selected";
break;
case 3: cout<<"Option3 is
selected";
break;
case 4: cout<<"Option4 is
selected;
break;
default: cout<<"Invalid option!";
}

Looping

A loop statement allows us to execute a statement or group of statements


multiple times and following is the general from of a loop statement in most of the
programming languages
C++ while and do...while Loop. Loops are used in programming to repeat a
specific block of code. ... In computer programming, loop repeats a certain block
of code until some end condition is met.
Types of Loop
1.Entry control Loop
i)For Loop
ii)While Loop
2.Exit Control Loop
i) Do while Loop

for Loop

1. The initialization statement is executed only once at the beginning.


2. Then, the test expression is evaluated.
3. If the test expression is false, for loop is terminated. But if the test
expression is true, codes inside body of for loop is executed and update
expression is updated.
4. Again, the test expression is evaluated and this process repeats until the test
expression is false.
Syntax

for(initializationStatement;
testExpression;increment/decreme
nt)

// codes

}
Example

for(i=0;i<=5;i++)

Cout<<” SRM IST”


}

while Loop

● The while loop evaluates the test expression.


● If the test expression is true, codes inside the body of while loop is
evaluated.
● Then, the test expression is evaluated again. This process goes on until the
test expression is false.
● When the test expression is false, while loop is terminated.
Syntax

while
(testExpression)

// codes

Example

I=0;

while (i<=5)

Cout<<” SRM
IST”

i++;

Do While Loop

The do...while loop is a variant of the while loop with one important difference.
The body of do...while loop is executed once before the test expression is checked.

● The codes inside the body of loop is executed at least once. Then, only the
test expression is checked.
● If the test expression is true, the body of loop is executed. This process
continues until the test expression becomes false.
● When the test expression is false, do...while loop is terminated.
Syntax

do

// codes;

while
(testExpression);

Example

do

Cout<<”SRM IST
“;

while (i<=5);

Example Program

Sum of n num (Lab program)

3. Datatypes in C++
1. Primary(Built-in) Data Types:
⮚ character
⮚ integer
⮚ floating point
⮚ boolean
⮚ double floating point
⮚ void
⮚ wide character

2.User Defined Data Types:

⮚ Structure
⮚ Union
⮚ Class
⮚ Enumeration
3.Derived Data Types:

⮚ Array
⮚ Function
⮚ Pointer

1.User Define Data type

The data types that are defined by the user are called the derived datatype or user-
defined derived data type.

Class:
The building block of C++ that leads to Object Oriented
programming is a Class. It is a user defined data type, which holds its own data
members and member functions, which can be accessed and used by creating an
instance of that class. A class is like a blueprint for an object.

Structure:
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.
Syntax
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Union:

union is a user defined data type. In union, all members share


the same memory location. For example in the following C program, both x and y
share the same location. If we change x, we can see the changes being reflected in
y.

Syntax

union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

Enumeration:

Enumeration (or enum) is a user defined data type in C. It is


mainly used to assign names to integral constants, the names make a
program easy to read and maintain.

Syntax

enum week
{
Mon,
Tue,
Wed,
Thur,
Fri,
Sat,
Sun
};
2.Built in Data Type

Data types in C++ is mainly divided into two types: Primitive Data Types:
These data typesare built-in or predefined data types and can be used directly by
the user to declare variables. example: int, char , float, bool etc.
:
These data types are built-in or predefined data types and can be used
directly by the user to declare variables. example: int, char , float, bool etc.

Integer: Keyword used for integer data types is int. Integers typically
requires 4 bytes of memory space and ranges from -2147483648 to 2147483647.
Character: Character data type is used for storing characters. Keyword used
for character data type is char. Characters typically requires 1 byte of memory
space and ranges from -128 to 127 or 0 to 255.
Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data type
is bool.
Floating Point: Floating Point data type is used for storing single precision
floating point values or decimal values. Keyword used for floating point data type
is float. Float variables typically requires 4 byte of memory space.
Double Floating Point: Double Floating Point data type is used for storing
double precision floating point values or decimal values. Keyword used for double
floating point data type is double. Double variables typically requires 8 byte of
memory space.
void: Void means without any value. void datatype represents a valueless
entity. Void data type is used for those function which does not returns a value.

3.Derived data types

1. Array
2. Function
3. Pointer
Array
An array is simply a collection of variables of the same data
type that are referenced by a common name. In other words, when elements of
linear structures are represented in the memory by means of contiguous memory
locations, these linear structures are called arrays.

An array stores a list of finite number (n) of homogeneous


data elements (i.e., data elements of the same type). The number n is called length
or size or range of an array.

Syntax

type array_name[array_size];

Example

Int arr[10];

Functions
A function declaration tells the compiler about a function's name, return
type, and parameters. A function definition provides the actual body of the
function. The C++ standard library provides numerous built-in functions that your
program can call.
Function prototype or function interface is a declaration of
a function that specifies the function's name and type signature (arity, data types
of parameters, and return type), but omits the function body.

Syntax

Function name ()
{
--------
--------
}

Pointers

& symbol is used to get the address of the variable. * symbol is used
to get the value of the variable that the pointer is pointing to. If a pointer in C is
assigned to NULL, it means it is pointing to nothing. Two pointers can be
subtracted to know how many elements are available between these two pointers.

The actual data type of the value of all pointers, whether integer,
float, character, or otherwise, is the same, a long hexadecimal number that
represents a memory address. The only difference between pointers of
different data types is the data type of the variable or constant that
the pointer points to.

Syntax

Int *a

4.Operators in C++

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipula

● Arithmetic Operators
● Relational Operators
● Logical Operators
● Bitwise Operators
● Assignment Operators

Arithmetic Operators

Operato Description Example


r

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200


/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after B % A will give 0


an integer division

++ Increment operator, increases integer A++ will give 11


value by one

-- Decrement operator, decreases integer A-- will give 9


value by one

Relational Operators

Operat Description Example


or

== Checks if the values of two operands (A == B) is not true.


are equal or not, if yes then condition
becomes true.

!= Checks if the values of two operands (A != B) is true.


are equal or not, if values are not
equal then condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right
operand, if yes then condition
becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand, if
yes then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is (A <= B) is true.


less than or equal to the value of right
operand, if yes then condition
becomes true.

Logical Operators
Operato Description Example
r

&& Called Logical AND operator. If both the (A && B) is false.


operands are non-zero, then condition
becomes true.

|| Called Logical OR Operator. If any of (A || B) is true.


the two operands is non-zero, then
condition becomes true.

! Called Logical NOT Operator. Use to !(A && B) is t


reverses the logical state of its operand. If
a condition is true, then Logical NOT
operator will make false.

Bitwise Operators
Operato Description Example Operato Description
r r
& Binary AND & Binary AND
Operator copies a bit Operator copies a bit
(A & B) will give 12
to the result if it to the result if it
which is 0000 1100
exists in both exists in both
operands. operands.

| Binary OR Operator (A | B) will give 61 | Binary OR Operator


copies a bit if it exists which is 0011 1101 copies a bit if it exists
in either operand. in either operand.

^ Binary XOR ^ Binary XOR


Operator copies the (A ^ B) will give 49 Operator copies the
bit if it is set in one which is 0011 0001 bit if it is set in one
operand but not both. operand but not both.

~ Binary Ones (~A ) will give -61 ~ Binary Ones


Complement which is 1100 0011 in Complement
Operator is unary and 2's complement form Operator is unary and
has the effect of due to a signed binary has the effect of
'flipping' bits. number. 'flipping' bits.

Assignment Operators
Operato Description Example
r

= Simple assignment operator, Assigns values


C = A + B will assign value of A + B
from right side operands to left side
into C
operand.

+= Add AND assignment operator, It adds right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to left operand.
-= Subtract AND assignment operator, It
subtracts right operand from the left
C -= A is equivalent to C = C - A
operand and assign the result to left
operand.

*= Multiply AND assignment operator, It


multiplies right operand with the left
C *= A is equivalent to C = C * A
operand and assign the result to left
operand.

/= Divide AND assignment operator, It divides


left operand with the right operand and C /= A is equivalent to C = C / A
assign the result to left operand.

%= Modulus AND assignment operator, It takes


modulus using two operands and assign the C %= A is equivalent to C = C % A
result to left operand.

Misc Operators
Sr.N Operator & Description
o

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.

4 . (dot) and -> (arrow)


Member operators are used to reference individual members of classes, structures,
and unions.

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.

You might also like