Chaperter#3
Object Oriented Programming
Introduction
C++ was developed by Bjarne Stroustrup at Bell
Laboratories in 1979
C++ is an attempt to add object-oriented features
(plus other improvements) to C
Earlier it was called as “C with Objects”
As the language developed, Stroustrup named it as
C++ in 1983
The name C++ suggests “C incremented” (recall the
++ is an increment operator of C)
The main difference between C and C++ is that C++
support classes and objects, while C does not
C++ was made available outside Bell Laboratories in
1985
The first commercial C++ compiler, Cfront, was
Computer Program
Set of instructions written in computer languages(using
IDEs)
To perform Specific Task for computer
Sequence of Instructions to do work
Program Tells the computer what to do
In which order to do
Mean when we add two number using specific Operation in
specific task
Many programming languages are used for different tasks
Example are C++,JAVA,SQL,HTML etc
Header Files and Reserved words
File containing information needed in programs
These information needed in programming
When we using Dev C++ to perform specific Task
Or multiple functions
Information about the these functions or task required help
Help present in Header files
Present in standard library of C++ compiler
In C++ multiple Header Files
For example Iostream.h, string.h, fstream.h, math.h etc
Extension of all Header Files is .h(header file)
# ( Preprocessor Directive) Identify Header file ( to read
specially)
#include(name)
Reserved Words
Special words
Reserved for specific purpose
Cannot be use as a variable names
Or function names
For example If, else ,while, for
Lowercase letters
Approximately 80 reserved words in C++
Structure of C++Program
Dev C++ compiler is a compiler
Compiler is a program to convert Human/High level
Language convert into Computer/Low level
language( Binary form)
Every C++ program has three parts:
Header file(Preprocessor directives)
Main()( contain all function executable statements for some
task
Body of the main function
No restriction on numbers of statements
Every program start from main function
Using Namespace
With the same name available in different libraries
Differentiate similar variable etc(add additional information)
Preprocessor Directives
Start with #
Already add to library
Two types
Include
Define
Include
Using when we add header file
Writing Method is #include< > or include” ”
#include< > is used header files provide by compiler or IDE
example Iostream, stdiostream, maths.h etc
Having own folder include
.h using when its used in file
With .h is mean its present in namespace
include” ” this header files is used for personal library or header
files
Add own creating header file and add in own library
Just myfile.h
Define Directives
#define ----
To made micros
Example I create a micro with name Size and
value 5
#define size 5
Mean every where we call size micro its mean
value 5
Main() Function
User define function
To define the logic inside the main function
Execution of program always start and end with main function
Each and every program has at least one function main function
Its important part of any program
Its contain any number of statements
Written method return-type Main()
Start and close with parenthesis ( inside the curly braces code writing)
Function having two type
First is User define function
To write user code in the curly braces
Void function() then { body}
Predefine function
System define fucntions end with semi-colon
Example Printf(); end with semi-colon
Body of the main() Function:
The statements enclosed between curly braces {} from the
body of the function
Any number of statements can be written in the body of the
main() function
Each statement inside the function must be terminated with
semi colon
Using the semi-colon to identify that statement is completed
Called statement terminater
Cout<<“Welcome to C++”;
C++ statement that display message “Welcome to C++” on
screen
“cout” object is used to display output on the screen
“cout” object is used with the insertion operator <<.
Anything written after the insertion operator is displayed on
the screen
Group of characters inside the quotations marks is called
string literal/string constant/simplay a string
“getch()” Function
Using to input single character from user
“getch()”
Get mean get and ch mean character
Required conio.h header file to use this function
When this function executed. It wait for any key to be
pressed and don’t need to press enter key
Character enter by the user is not displayed on the screen
Commonly used at at the end of program
To stop screen
“getch();”
Another way to use this function is as follows:
“variable=getch();”
Variable indicate the variable in which the character is stored
Return:
Statement causes the main function
To return control to the operating system
returns the flow of the execution to the function from
where it is called
does not mandatorily need any conditional statements
statement is executed, the flow of the program
stops immediately and returns the control from
where it was called
Statement terminator:
In c++ every statement terminated by semicolon(;)
“;” called terminator
the end of each statement in C++ specifies the
distinction between statements
doesn’t matter if you put many statements on a single
line
Comments and Their Syntax In C++
Comments are pieces of source code that the
compiler ignores
No effect other than to make the code more readable and
understandable
Allow programmers to add comments or descriptions to the
source code
There are two sorts of comments in C++
Single Line Comments In C++:
The double slash // symbol represents it
Present everything from where the pair of slashes
signs // is found to the end of the same line
Multi or Double Line Comments In C++
The symbol /*....... */ is used to indicate double-line
comments
The compiler ignores everything between these two symbols
When programmers require several line comments, this
form of comment is used.
Constant and variable
A constant is a value
Never change
During the execution of a program
Fixed value
Two types
Numeric constant
Character constant
Numeric Constant:
Hold only number
Or store only number data
Numeric constant having two types:
Integer constant
Real constant
Integer constant:
Complete number
Example 1,2,3,6, -4,-10 etc
Real constant or Float constant:
Decimal number/ point value hold
Example 3.5,7.5, -8.3 etc
Character constant:
To hold character constant
Using single quotation
Example ‘a’ ‘Hello’
Two types:
Single character constant:
Hold single character
Example ‘a’ , ‘A’ etc
String constant:
Hold multiple character constantly
Example ‘hello’ ‘Hello’
Variable
Value not fixed
Reside inside the RAM
Use for storing data
Temporary storage
Example
“int a = 5;
“int b = 2;
Result = a – b;
In this a & b are integers
Reside in the RAM
Store integer values
Rules for naming variables
1. Valid identifier is sequence of one or more letters,
digits or underscore character
2. No space in naming
3. Always start with letter or
4. Begin with underscore character(_)
5. Can’t begin with digit
6. Can’t reserved word of C++ used as an variable
name
7. Name should be meaningful
8. Name should not be too long
9. C++ case sensitive means that an variable written in
capital letters is not equivalent to the one written in
small letters.
Declaration and initialization of variables
Declaration of variables:
To use a variable first declare it
Declare mean mean which data type store it
Using different data types
Such is int, bool, float, char etc
Declaration method
Data type variable_name;
“ int a;
“char a;
“float b;
“ int a, b, c ,
More then one variables of same type can be declare in
a single statement by separating them with commas,
Initialization of variables
After the declaration of variable to assign the value
Given a value to a variable
Initialization is the process of assigning a value to the
Variable
Example
“int var = 4;
“int is data type
“var is name of variable
“ 4 is value assign to variable in programming
Fundamental data type in C++
To store the value in memory
Use variables in programming for storing value
Different data types of variables to store data
Data types tell the compiler what type data store
during the initialization
Most commonly used data types in C++ are below:
Character data type
Integer data type
Floating data type
Boolean data type
Unsigned data type
Character data type:
Datype that is used to store characters
define Character in C++ we use char keyword
Size of char data type is 1 byte i.e 8 bits
Range 0-255
Syntax:- char a;
Integer data type
data type that is used to store integer values
define Integer in C++ we use int keyword
Size of int datatype is 4 byte i.e 32 bits
It's range is from -2147483648 to 2147483647
Three types of integer data types:
Short int data type:
It store only integers value
2 bytes or 16 bits
-2 power15 to 2 power 15
Long int data types:
Same as integer
4 byte or 32 bits data storage
Range -2147483648 to 2147483648
Floating Point Data type:
Integer are only storing whole number
To store decimal point number using this data type
Hold float number
Example are 3.4, .78 etc
Types of floating data types are:
Float point data type:
Store decimal data
Size 4 byte or 32 bits
Double data type:
Store decimal data
Size 8 byte or bits
Long double data type:
Store decimal data
Using for long floating point number
Size 10 bytes
Boolean data type:
Boolean mean two
True or falls
Size 1 byte or 8 bits
Store data in 0 & 1 form
Unsigned data type:
One bit store sign of the value
All are whole number
All are positive number
Starting from 0
Used to store 32-bit integers
Types of Unsigned data types are:
Unsigned char
Signe only positive value
'myHeight' to hold your height, you could make it
unsigned because you know that you would never be
negative inches tall
Unsigned integer
holds values from -32768 to 32767
Hold only Positive value
Unsigned short integer
Unsigned long integer
constant qualifier in c++:
explicitly declares a data object
Value cannot be changed.
value is set at initialization
const has a very big benefit
For example, if you have a constant value of the value of PI
should declare that as a const
Objects declared with const-qualified types may be placed
in read-only memory by the compiler
#include<iostream>
using namespace std; int
main()
{ const int x = 10;
x = 12;
return 0;
}
Types of casting operator
Cast is a special operator
forces one data type to be converted into another
Example int a = 10; // a=10,
float b = (float)a; // 10.00
Type of casting operator are:
Implicit typecasting:
Conversion of operator
Compiler itself convert
Programmer don’t not any code written
Exmaple int a=10;
Double a2=a;
Output show in a value
Explicit type casting operator in C++:
Convert value
Explicit conversion
Programmer written code
Conversion control are programmer
Example written method:
int a = 10;
dobule a2 = (dobule)a;
Input output handling
The C++ standard libraries provide an extensive set
of input/output capabilities
in subsequent chapters
C++ I/O occurs in streams, which are sequences of
bytes
If bytes flow from a device like a keyboard, a disk
drive, or a network connection
to main memory, this is called input operation
if bytes flow from main memory to a device like a
display screen, a printer, a disk drive, or a network
connection, etc., this is called output operation
Standard Output Stream (cout)
The predefined object cout is an instance
of ostream class
The cout object is said to be "connected to" the
standard output device
To display screen
The cout is used in conjunction with the stream
insertion operator
Statement written as << which are two less than signs
Example cout << "Value of str is : " << str << endl;
The Standard Input Stream (cin):
The predefined object cin is an instance of istream class
The cin object is said to be attached to the standard
input device
Usually is the keyboard
The cin is used in conjunction with the stream
extraction operator
written as >> which are two greater than signs
cout << "Please enter your name: ";
Functions In C++;
gets() function:
function reads characters from stdin and stores
Define in stdio.h header file
Used to get string from keyboard
Syntax is:
gets(string variable name);
puts() function;
Used to read characters or operators
Show on the screen
General syntax is :
Puts(string variable);
getch() function:
Used to input single character from the user
Required conio.h header file to use this function
When this function is executed I wait for any key to be
pressed
Then key used is input
Not display in on the screen
Used for execution pause installation
Syntax is getch();
Variable = gech();
The Escape Sequence:
special non-printing characters
used to control the printing behavior/Formate of
the output stream objects
characters are not displayed in the output
These are written in single or double-quotes
Used special character “\” back slash
For example, the escape sequence ‘\n’ is used
to insert a new line
Cout<<”\nWelcome”;
Input output Handling functions
Giving something to computer is known is input
Getting something from computer is known is output
Input:
cin: is used to input data form the keyboard
Assign to one aor more variables
Syntex: cin>>variable;
cin: name of object used to get standard input
>>:it is known as extraction operation. It gets the
input from cin object
Variable: in which the input value is stored ( headerfile)
getch() function is used to get singe character form
standard input device
Getch() define in sdtio.h header file
Writtern “int getch();”
Output:
Cout:is used to output text or value on the screen
Syntax: cout<<variable/const/exprission;
cout: name of object used to display standard
output
<<: known is insertion operation or put to
operator, used for to send output to cout object
Variable: whose value is display on screen ( form
headerfile)
Putch() to diplay on the screen
end manipulator:
Use for output formatting
Same just like \n fo
for newline character
Syntax method
cout<<“Sr.”<<setw(space
cahracters)<<“Name”<<setw(10)<<“Marks”;
Using header file <iomanip>
#include <iomanip>
#include <ios>
#include <iostream>
main()
{ cout<<“S.No”<<setw(10)<<“StName”<<setw(10);}
Operators In C++
Operators are symbols
Perform operation on Operands
z=x+y
x, y, z are operands and “+” are Operator
C++ having multiple supported wide range of Operators
Example int x = 100 + 50;
Some operators are below:
Arithmetic Operators:
Arithmetic operators are used to perform common
mathematical operations.
Five arithmetic operators used in C++
+ is used for addition
- is used for subtraction
* is used for multiplication
% is used for modulus ( reminder of two digits)
Assignment Operators:
Assignment operators are used to assign values to
variables
Example
assignment operator (=) to assign the value 10 to a
variable called x:
int x = 10;
Compound operator or arithmetic assignment Operator:
Used in C++
Modify the value of a variable
Perform operation
Example
x *= 3;
Increment ++ and Decrement -- Operator
In programming (Java, C, C++, JavaScript etc.),
the increment operator are used
++ increases the value of a variable by 1
Similarly, the decrement operator -- decreases
the value of a variable by 1
++ and -- operator as prefix and postfix
If you use the ++ operator as a prefix like: +
+var, the value of var is incremented by 1; then
it returns the value.
If you use the ++ operator as a postfix
like: var++, the original value of var is returned
first; then var is incremented by 1.
The -- operator works in a similar way to the +
+ operator except -- decreases the value by 1.
Relational operators
Used for comparison between two expressions
The result of these operators can be true or
false
Some C++ relational operators are below
<,>,>=,<= etc
Example
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5
is greater than 3
Logical operators
Compare two values (or variables)
Important in programming, because it helps us
to find answers and make decisions
The return value of a comparison is
either 1 or 0
which means true (1) or false (0)
These values are known as Boolean values
Some Logical operators in C++ are below:
!(not), &&(both true are false) etc
! C++ unary operator
Used for Boolean operation
Logical NOT Operator:
Unary operator
Used for Boolean Not operation
Out put is inverse of the value
Logical AND operator:
Need two operands
Used if both condition true or not
Logical OR operator:
ll symbol used
Test true or false
One true result true
Both true result true
Both false result false
Unary Operator:
Operators which need a single Operand
Example x=-y or a=+b
Or logical operator is also unary operator
Example ! Etc
Binary operators:
Operators as it requires two operands
Example x= a + b etc
Ternary operators:
Operators which need three operands
example x=a+b+c
Precedence Operators in C++:
Which operand will be evaluated first and
which one evaluated later if complex
expression
Rules for evaluation of complex expression:
The parentheses are evaluated first
Then multiplication
Division
Modulus
Addition
Subtraction operators are evaluated at last