Unit 1
Unit 1
OBJECT
ORIENETED
PROGRAMMING
IN C++
UNIT I
OBJECT ORIENTED CONCEPTS
• C++ Operators and control statements- Input and output statements- Function
Prototyping-Function components- Passing parameters - call by reference, return by
reference- Inline function- Default arguments - Overloaded function- Introduction
to friend function.
UNIT II
CLASSES AND OBJECTS, CONSTRUCTORS AND DESTRUCTORS
#include<iostream>
using namespace std;
int main()
{
cout<<“Hello World”;
return 0;
Output:
} Hello World
Structure of
C++ (PoP)
1. Header File
• The header files contain the definition of the functions and macros.
• They are defined on the top of the C++ program.
• The #include <iostream> statement to tell the compiler to
include an iostream header file library which stores the definition
of the cin and cout standard input/output streams that we have
used for input and output.
• #include is a preprocessor directive using which we import
header files.
• Syntax:
#include <library_name>
2. Namespace
• A namespace in C++ is used to provide a scope or a region where we
define identifiers.
• It is used to avoid name conflicts between two identifiers as only unique
names can be used as identifiers.
• In line #2, we have used the using namespace std statement for
specifying that we will be the standard namespace where all the standard
library functions are defined.
• Syntax:
using namespace std;
3. Main Function
• Functions are basic building blocks of a C++ program that contains the
instructions for performing some specific task.
• A function definition also contains information about its return type and
parameters.
• In line #3, we defined the main function as int main(). The main function
is the most important part of any C++ program. The program execution
always starts from the main function.
• All the other functions are called from the main function. In C++, the main
function is required to return some value indicating the execution status.
• Syntax:
int main()
{
... code ....
return 0;
}
4. Blocks
• Blocks are the group of statements that are enclosed within { } braces.
• They define the scope of the identifiers and are generally used to enclose
the body of functions and control statements.
• The body of the main function is from line #4 to line #9 enclosed within
{ }.
• Syntax:
{
Statements;
}
5. Semicolons
• It is used to terminate each line of the statement of the program.
• When the compiler sees this semicolon, it terminates the operation of that
line and moves to the next line.
• Syntax:
any_statement ;
6. Identifiers
• Use identifiers for the naming of variables, functions, and other
user-defined data types.
• An identifier may consist of uppercase and lowercase
alphabetical characters, underscore, and digits.
• The first letter must be an underscore or an alphabet.
• Example:int num1 = 24; //num1 is identifiers
7. Keywords
• In the C++ programming language, there are some reserved words that
are used for some special meaning in the C++ program.
• It can’t be used for identifiers.
• There are total 95 keywords in C++.
• Example:
• int void if while for auto bool break
Structure of
C++ (ooP)
1. Class
• A class is a template of an object. It is a user-defined data type.
• A class has its own attributes (data members) and behavior (member
functions).
• The first letter of the class name is always capitalized & use the class
keyword for creating the class.
• Syntax:
class class_name
{
// class body
};
2. Data Members & Member Functions
• The attributes or data in the class are defined by the data members & the
functions that work on these data members are called the member
functions.
• There is a keyword here public that is access modifiers. The
access modifier decides who has access to these data
members & member functions.
• public access modifier means these data members & member
functions can get access by anyone.
3. Object
• The object is an instance of a class. The class itself is just a template that is
not allocated any memory.
• To use the data and methods defined in the class, we have to create an
object of that class.
• Use dot operator ( . ) for accessing data and methods of an object.
• Syntax:
class_name object_name;
Applications
of C++
Tokens
• The smallest individual units in program are known as tokens. C++ has
the following tokens.
i. Keywords
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
Identifiers:
• Identifiers are names given to various entries, such as variables,
structures, and functions. Also, identifier names must be unique as
these entities are used in program execution.
• int student_age = 25; // student_age is an integer variable or identifier
• Naming style of Identifiers:
• Must begin with an alphabet character (A-Z or a-z) or an
underscore(_).
• An Identifier consists of characters, numbers and underscore.
• Blank space and Special characters should not be used in identifier
declaration.
• Not exceed 31 characters.
• Case sensitive.
• Can't use keyword as identifiers.
Valid
Identifiers Invalid Identifiers
name
123name
NAME
%name
_Name
stud name
Name_
any keywords like
Name123
int, string, etc.
_name_
Keywords
• Keywords are reserved words with
fixed meanings that cannot be
changed.
• The meaning and working of these
keywords are already known to the
compiler.
• C++ has more numbers of
keywords than C, and those extra
ones have unique working
capabilities.
• auto: declares a variable as 'automatic' type. • else: Executes a block of code when an if
• break: used inside loop for sudden termination condition is false.
if required. • enum: Declares an enumeration.
• case: used within 'switch' statement where • explicit: Specifies that a constructor or
redirecting occurs on choice. conversion function should not be implicitly
• default: used within 'switch' statement where invoked.
redirecting occurs on wrong choice. • extern: Declares that a variable or function is
• char: used to declare a character type variable. defined externally.
• class: used to declare a class type variable. • float: Declares a single-precision floating-point
type.
• const: declares a constant variable which cannot
be changed. • for: Starts a for loop.
• continue: Jumps to the next iteration within a • friend: Declares a function or class as a friend,
loop. allowing it to access private members of
another class.
• delete: Deallocates memory for an object created
with new. • goto: Transfers control to a labeled statement.
• do: Starts a do-while loop. • if: Specifies a conditional statement.
• double: Declares a double-precision floating-
point type.
• inline: Suggests to the compiler to perform in- • return: Returns a value from a function.
lining, i.e., to insert the complete body of the • short: Declares a short integer type.
function at the point of the call.
• signed: Declares a signed integer type.
• int: Declares an integer type.
• sizeof: Returns the size, in bytes, of a type or
• long: Declares a long integer type.
object.
• namespace: Declares a scope that contains a •
static: Specifies that a variable or function is
set of identifiers. static, meaning it retains its value or scope
• new: Allocates memory for an object or an throughout the program's execution.
array. • struct: Declares a structure.
• operator: Declares an operator function. • switch: Starts a switch statement.
• private: Specifies that class members are •
template: Specifies a template for generic
accessible only within the class. programming.
• protected: Specifies that class members are •
this: A pointer that points to the current object.
accessible within the class and its subclasses.
• throw: Throws an exception.
• public: Specifies that class members are
accessible from outside the class. • try: Specifies a block of code to be tested for
exceptions.
• register: Suggests to the compiler to store the
variable in a register for faster access. • typedef: Defines a new type using an existing
type.
• union: A data structure that allows storing different types of data in the same
memory location is called union.
• unsigned: It declares an unsigned integer type.
• using: It introduces a name from a namespace into the current scope.
• virtual: It specifies that a function can be overridden in a derived class.
• void: Means that a function or a pointer does not return a value
• volatile: It means that a variable can be changed outside of the program.
• Operators
• C++ operator is a symbol that
is used to perform
mathematical or logical
manipulations.
• Other Operators in C++
>> cin >> num; Used to take input from command line
Constants
• Constants are like a variable,
except that their value never
changes during execution once
defined.
• There are two common types of
constants in C++
• Literal constant
• Symbolic constant
• A symbolic constant is a name given to values that cannot be changed. A
constant must be initialized.
• After a constant is initialized, its value cannot be changed.
• Symbolic constants are used to represent a value that is frequently used in a
program.
• Symbolic constants can be declared in two ways:
• Const Qualifier: Const data-type identifier = value;
• Example: Const int N = 100;
• Define Directive: #define identifier value
• Example: # define PI 3.1411596
Strings
• A string in C++ is an object that represents a sequence of characters.
• Strings in C++ are a part of the standard string class
(std::string)
• Syntax:
• string object_name= value;
• charAt(index) used to access the character of string.
Data types:
• A data type defines the type and the set of operations that can be
performed on the data.
• The data is given as an input to the program. According to the
program's set of instructions, data is processed and then output is
returned on the screen.
• Before designing the actual program data, its type and operations
performed on it are defined and used to process the data.
• At the start of the program, the type of each data value is identified.
Integer
Character
• Characters are stored by using character data type.
• Char is used to representing character data type.
• It normally requires 1 byte of memory.
• As each character is assigned by a unique ASCII code which is an
integer so that’s why characters are included in integral data type.
• When we store a character in memory, we actually store a unique
numeric code associated with that character in memory.
• And when the computer is instructed to print characters, it basically
prints characters associated with the numeric code.
void
• The type void normally used for:
1) To specify the return type of function when it is not returning any
value.
2) To indicate an empty argument list to a function.
Example:
Void function(void);
Another interesting use of void is in the declaration of genetic
pointer
Example:
Void *gp;
float
• A float data type is used to store real numbers or large numbers with a fractional
component like 1.0,14.01,23.45,-21.560,191.123456, etc. The part after the decimal is
known as its fractional component.
• 1-bit for the sign, 8-bit for exponent, 23-bit for the value or mantissa.The size of a
float is 4-bytes(32 bit)
• why the name ‘float’?
• Decimal is referred to as floating-point because we can observe from above that decimal
supports a variable number of digits before and after it, which means decimal point can float
between the numbers. Thus the name float data type comes from the floating-point.
• Syntax:
• float variable_name;
• Example:
• float a;
• float a=3.5;
double
• Double data type in C++ is a versatile data type that can represent any numerical value in the
compiler, including decimal values.
• There are two types of double data types in C++: whole numbers as well as fractional numbers with
values.
• It takes 8byte of Memory.
• The compiler in C++, by default, treats every value as a double and implicitly performs a type
conversion between different data types.
• Syntax:
• double variable_name;
• Example:
• double var_1, var_2, var_3;
• double var1 = 5.999999;
• double var2 = 5.0;
• double var3 = 5;
• double var4 = -5.0000;
User Defined Data
Types struct Person {
string first_name;
string last_name;
int age;
STRUCTERS
float salary;
• A structure is a user-defined data type in C/C+ // member function to display information
+. A structure creates a data type that can be
used to group items of possibly different types
about the person
into a single type. void displayInfo()
{
• In C++, structures can also have member
functions. cout << "First Name: " << first_name << endl;
cout << "Last Name: " << last_name << endl;
• Syntax:
cout << "Age: " << age << endl;
struct structure_name
cout << "Salary: " << salary << endl;
{
}
Data elements
};
Member functions
};
union Person {
Union string first_name;
• Union is a datatype defined by the string last_name;
user, and all the different members int age;
of the union have the same memory float salary;
location.
// member function to display information
• The member of the union, which about the person
occupies the largest memory,
decides the union’s size. void displayInfo()
• In C++, structures can also have {
member functions. cout << "First Name: " << first_name << endl;
Syntax: cout << "Last Name: " << last_name << endl;
union union_name cout << "Age: " << age << endl;
{ cout << "Salary: " << salary << endl;
data elements }
Member functions };
};
CLASSES
• C++ also permits us to define another
user defined data type known as class
which can be used just like any other
basic data type to declare a variable. The
class variables are known as objects,
which are the central focus of oops.
Syntax :
class classname
{
Data members
Function members
};
Enum:
• An enumerated data type is another #include <iostream>
user defined type which provides a way using namespace std;
for attaching names to number, these by
increasing comprehensibility of the enum week { Sunday, Monday, Tuesday,
code. Wednesday, Thursday, Friday, Saturday };
• The enum keyword automatically
enumerates a list of words by assigning int main()
them values 0,1,2 and soon. This facility {
provides an alternative means for week today;
creating symbolic. today = Wednesday;
cout << "Day " << today+1;
return 0;
}
Array
• An array is a variable which can store multiple values of same data type at a time
or Collection of similar data items stored in continuous memory locations with
single name.
int a[3];
a[1]=100;
• Arrays are classified into two types. They are as follows...
Single Dimensional Array / One Dimensional Array
• In c programming language, single dimensional arrays are used to store list of values of same
datatype. single dimensional arrays are used to store a row of values.
• Syntax: datatype arrayName [ size ] ; or
datatype arrayName [ ] = {value1, value2, ...} ;
• Example: int rollNumbers [60] ;
• int marks [] = { 89, 90, 76, 78, 98, 86 } ;
• char studentName [] = "btechsmartclass" ;
Multi Dimensional Array
• An array of arrays is called as multi dimensional array. In simple words, an array created with
more than one dimension (size) is called as multi dimensional array. Multi dimensional array
can be of two dimensional array or three dimensional array or four dimensional array or more...
• Syntax:datatype arrayName [ rowSize ] [ columnSize ] ;
• Example: int matrix_A [2][3] ;
• int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
int i, *ptr; float f;
Pointer i = 10; // Allowed
• A pointer is a special type of variable used to store ptr = &i; // Allowed
the address of another variable of same data type. ptr = &f; // Not allowed - Data type
mismatch
• The pointer variable may be of any data type, but
ptr = 65524; // Not allowed - Dirct value
every pointer can store the address of same data
type variable only. That means, an integer pointer not accepted
can store only integer variable address and float
pointer can store only float variable address.
• Creating a pointer
• Syntax: data_type *variable_name; or data_type*
variable_name;
• Example: int *ptr; or int* ptr;
• To access Value:
int i, *ptr;
i = 10;
ptr = &i;
cout << "Value of i = " << *ptr << endl;
DECLARATION OF VARIABLES:
• In ANSI 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 and forth. It also makes the
program easier to understand because the variables are declared in the
context of their use.
int main( )
{
float x,average;
float sum=0; P.T.O 24
for(int i=1;i<5;i++)
{
cin>>x;
sum=sum+x
}
float average;
average=sum/x;
cout<<average;
}
REFERENCE VARIABLES:
• C++interfaces a new kind of variable known as the reference variable.
• A references variable provides an alias.(alternative name) for a
previously defined variable.
• A reference variable is created as follows:
Syntax: Datatype & reference–name=variable name;
• 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.
float total=1500;
float &sum=total;
• A reference variable must be initialized at the time of declaration .
SCOPE RESOLUTION OPERATOR:
• Like C,C++ is also a block-structured language. Block -structured
language.
• Blocks and scopes can be used in constructing programs.
• We know same variables can be declared in different block
because the variables declared in blocks are local to that function.
• Syntax: : : variable –name;
#include <iostrcam.h> cout<<”\n we are in outer
int m=10; block \n”;
main() cout<<"m="<<m<<endl;
{ cout<<":: m="<<:: m<<endl;
int m=20; }
{
int k=m;
int m=30;
cout<<”we are in inner block”;
cout<<"k="<<k<<endl;
cout<<"m="<<m<<endl;
cout<<":: m="<<:: m<<endl;
}
Type Modifiers
• There are some modifiers in C++ that allow us to alter the meaning of base types
like int, char, and double. The modifiers are as follows:
• signed - Used for both positive and negative values
• unsigned - Used for only positive values
• long - Used to increase the size of data-types
• short - Used to reduce the size of data-types
• Link: https://www.scaler.com/topics/cpp/modifiers-in-cpp/
Type Casting
• In a c programming language, the data conversion is performed in two different methods as follows.
• Type Conversion
• Type Casting
• Type Conversion
• The type conversion is the process of converting a data value from one data type to another data
type automatically by the compiler.
• Sometimes type conversion is also called implicit type conversion. The implicit type conversion
is automatically performed by the compiler.
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
i = x ; =======> x value 15.5 is converted as 15 and assigned to variable i
x = i ; =======> Here i value 10 is converted as 10.000000 and assigned to variable x
i = ch ; =======> Here the ASCII value of A (65) is assigned to i
• Typecasting
• Typecasting is also called an explicit type conversion. Compiler converts data
from one data type to another data type implicitly. When compiler converts
implicitly, there may be a data loss.
• In such a case, we convert the data from one data type to another data type using
explicit type conversion. To perform this we use the unary cast operator.
• Syntax: (TargetDatatype) DataValue
• Example: float average=(float)500/5;
Operators
• In C++ language, the operators are classified as follows.
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Increment and Decrement Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators
• Scope Resolution Operators
• Other Operators
Arithmetic Operators (+, -, *, /, %)
• The arithmetic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo. The following table provides information about arithmetic
operators.
Relational Operators (<, >, <=, >=, ==, !=)
• The relational operators are the symbols that are used to compare two values. That
means the relational operators are used to check the relationship between two
values. Every relational operator has two results TRUE or FALSE.
Logical Operators (&&, ||, !)
• The logical operators are the symbols that are used to
combine multiple conditions into one condition.
Increment & Decrement Operators
(++ & --)
• The increment and decrement operators are called unary operators because both
need only one operand.
• The increment operators adds one to the existing value of the operand and the
decrement operator subtracts one from the existing value of the operand.
• The increment and decrement operators are used infront of the operand (++a) or
after the operand (a++).
• If it is used infront of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-
decrement.
Assignment Operators (=, +=, -=,
*=, /=, %=)
• The assignment operators are used to assign right-hand
side value (Rvalue) to the left-hand side variable
(Lvalue). The assignment operator is used in different
variants along with arithmetic operators.
Bitwise Operators (&, |, ^, ~, >>,
<<)
• The bitwise operators are used to perform bit-level operations in the c++ programming
language. When we use the bitwise operators, the operations are performed based on the
binary values.
Conditional Operator (?:)
• The conditional operator is also called a ternary operator because it
requires three operands. This operator is used for decision making. In
this operator, first we verify a condition, then we perform one
operation out of the two operations based on the condition result. If
the condition is TRUE the first option is performed, if the condition is
FALSE the second option is performed. The conditional operator is
used with the following syntax.
• Syntax: Condition ? TRUE Part : FALSE Part;
• Example code: A = (10<15)? 100 : 200; // ⇒ A value is 100
Other Operators
• Scope Resolution Operator (: :)
• sizeof operator: sizeof(variableName);
• Pointer operator (*)
• Comma operator (,)
• Dot operator (.)
The operators are also classified based on the number of operands required by the
operator.
Unary Operators
- Requires only one operand like ++ and --.Binary Operators
- Requires two operands like +, *, ==, ||, >>, etc.Ternary Operators
- Requires three operands like conditional operator.
Control Flow Statement Types
if else…
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
Switch Statements
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the
Weekend";
}
For Loop
// noinit.cpp: for loop without initialization
and updation
#include <iostream>
using namespace std;
int main()
{
int i = 1;
for( ; i<=10; )
{
cout << i*5 <<" " ;
++i;
}
}
Break
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
}
cout << i << "\n";
}
While Loops
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Do/While Loop
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Continue
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
cout << i << "\n";
}
Goto
for (int i = 0; i < 10; i++) {
if (i == 4) {
goto final;
}
cout << i << "\n";
Final:
break;
}
Input and output statements
• Header files available in C++ for
Input/Output operations are:
int main()
{
cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0;
}
Parameter Passing
Parameter Passing
• Parameter passing is a mechanism for communication
of data and information between the calling
function(caller) and the called function(callee).
• Three types of parameter-passing schemes:
• Pass by Value
• Pass by References
• Pass by Address or pass by Pointer
• The formal parameters are those specified in the
function declaration and function definition.
• The actual parameters are those specified in the
function call.
Pass by Value
• The default mechanism of parameter passing is called
pass by value.
• This method is also called as call by value.
//value.cpp
#include <iostream>
using namespace std;
void fun(int a)
{
a=20;
}
int main()
{
int a =10;
fun(a);
cout<<"Value of A: "<<a<<endl;
return 0;
}
Pass by Reference
• In case of pass by reference, we pass argument to the
function at calling position.
• That reflects changes into parent function.
• Scope of modification is reflected in calling function
also.
• This method is also called as call by references.
//reference.cpp
#include <iostream>
using namespace std;
cout<<"Value of A: "<<a<<endl;
return 0;
}
Pass by Address or pass by Pointer
• In case of pass by reference, we pass argument to the
function at calling position.
• That reflects changes into parent function.
• Scope of modification is reflected in calling function
also.
//address.cpp
#include <iostream>
using namespace std;
void fun(int *b)
{
*b=20;
}
int main()
{
int a =10;
fun(&a);
cout<<"Value of A: "<<a<<endl;
return 0;
}
Inline Function
Inline Function
• Execution of a normal function call involves
the operation of saving actual parameter
and function return address onto the stack
followed by a call to the function.
• On return, the stack must be cleaned to
restore the original status.
• Inline functions are those whose function
body is inserted in place of the function-call
statement during the compilation process.
• Programs with inline functions execute
faster than programs containing normal
functions(non inline)
// square.cpp: square of a number using inline
function
#include<iostream>
inline int sqr( int num )
{
return num*num;
}
int main()
{
float n;
cout<< "Enter a number: ";
cin >> n;
cout << "Its Square = " << sqr(n) << endl;
cout << "sqr( 10 ) = " << sqr( 10 );
}
FUNCTION
OVERLOADING
Function Polymorphism or Function
Overloading
• Assigning one or more function bodies to the same
name is known as a function overloading or function-
name overloading.
// Show.cpp: display void show( char *val )
different types of {
information with same
function cout << "String: " << val
<< endl;
#include <iostream>
}
using namespace std;
int main ()
void show( int val )
{
{
show( 420);
cout << "Integer: " << val
<< endl;
} show(3.1415 );
void show( double val )
{ show("Hello World\n!");
cout << "Double: " << val }
<< endl;
}