OOPS Unit 1 & 2 Notes
OOPS Unit 1 & 2 Notes
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.
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.
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.
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.
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
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.
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.
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++.
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
1.Branching
2.Looping
Branching statement
⮚ if statement
⮚ if..else statements
⮚ if-else-if ladder
⮚ nested if statements
⮚ switch statements
If Statement:
Syntax
if (condition)
{
statement 1;
statement 2;
statement 3;
}
Example
if (mark>40)
Cout<<”PASS”;
}
If-else Statement:
if (condition)
// condition is true
else
// condition is false
Example
if(x>y)
cout<<”X is greater”;
else
cout<<”y is greater”;
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
for Loop
for(initializationStatement;
testExpression;increment/decreme
nt)
// codes
}
Example
for(i=0;i<=5;i++)
while Loop
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
3. Datatypes in C++
1. Primary(Built-in) Data Types:
⮚ character
⮚ integer
⮚ floating point
⮚ boolean
⮚ double floating point
⮚ void
⮚ wide character
⮚ Structure
⮚ Union
⮚ Class
⮚ Enumeration
3.Derived Data Types:
⮚ Array
⮚ Function
⮚ Pointer
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:
Syntax
union address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
Enumeration:
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.
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.
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
Relational Operators
Logical Operators
Operato Description Example
r
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.
Assignment Operators
Operato Description Example
r
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.
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.