Unit I Introduction to OOP
Unit I Introduction to OOP
The C++ program is written using a specific template structure. The structure of the program
written in C++ language is as follows:
Documentation Section:
This section comes first and is used to document the logic and purpose of the program.
Documentation section is the comment and is not compiled by the compiler. It is optional and
the program can execute without them.
Link Section-
The linking section contains two parts:
Header Files:
In order to use pre-defined elements in a program such as built-in functions, classes,
keywords, constants, operators, etc.(which are defined in the standard C++ library), an
appropriate header must be included in the program.
Standard headers(iostream) are specified in a program through the preprocessor
directive #include. When the compiler processes the instruction #include<iostream>, it includes
the contents of the stream in the program. This enables the programmer to use standard input,
output, and error facilities that are provided only through the standard streams defined in
<iostream>. These standard streams process data as a stream of characters, that is, data is read
and displayed in a continuous flow. The standard streams defined in <iostream> are listed here.
#include<iostream>
Namespaces:
A namespace permits grouping of various entities like classes, objects, functions, and
various C++ tokens, etc. under a single name.
Any user can create separate namespaces of its own and can use them in any other program.
namespace std contains declarations for cout, cin, endl, etc. statements.
Definition Section:
It is used to declare some constants and assign them some value.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
In this section, anyone can define your own datatype using primitive data types.
In #define is a compiler directive which tells the compiler whenever the message is found to
replace it with given string.
Global Declaration Section:
The variables and the class definitions which are going to be used in the program are declared
to make them global.
The scope of the variable declared in this section lasts until the entire program terminates.
These variables are accessible within the user-defined functions also.
Function Declaration Section:
It contains all the functions which our main functions need.
Usually, this section contains the User-defined functions.
This part of the program can be written after the main function but for this, write the function
prototype in this section for the function which for you are going to write code after the main
function.
Main Function:
The main function tells the compiler where to start the execution of the program. The execution
of the program starts with the main function.
All the statements that are to be executed are written in the main function.
The compiler executes all the instructions which are written in the curly braces {} which
encloses the body of the main function.
Once all instructions from the main function are executed, control comes out of the main
function and the program terminates and no further execution occur.
#include<iostream>
int main()
cout<<"Hello World"<<endl;
return 0;
#include<iostream>
int main()
cout<<msg<<endl;
Mrs. P.D.Titavekar
Object Oriented Programming using C++
return 0;
#include<iostream>
void display();
int main()
display();
return 0;
void display()
cout<<"Hello World";
4. /* Print hello world using scope resolution operator that iswithout namespace use */
#include<iostream>
int main()
std::cout<<"Hello World"<<std::endl;
return 0;
Mrs. P.D.Titavekar
Object Oriented Programming using C++
int main() {
int a, b, sum=0;
sum = a+b;
// prints sum
return 0;
Class
A Class in C++ is a blueprint representing a group of objects which shares some common
properties and behaviors.
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to manipulate
these variables together these data members and member functions define the properties and
behavior 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.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
Object
An Object is an identifiable entity with some characteristics and behavior. 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.
// C++ Program to show the syntax/working of Objects as a
#include <iostream>
class person {
char name[20];
int id;
public:
void getdetails() {}
};
int main()
return 0;
Objects take up space in memory and have an associated address like a record in structure or union.
When a program is executed the objects interact by sending messages to one another.
The wrapping up of data and function into a single unit is known as Encapsulation.
Abstraction
Abstraction means displaying only essential information and hiding the details. Data abstraction
refers to providing only essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerator will increase the speed of the car or applying brakes will stop the car but he does not
Mrs. P.D.Titavekar
Object Oriented Programming using C++
know how on pressing the accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of an accelerator, brakes, etc. in the car. This is
what abstraction is.
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 characteristics. A man at the same time is a father, a husband, and an employee. So
the same person possesses different behavior in different situations. This is called polymorphism.
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 a sub-class is called Base Class or
Superclass.
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.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
Dynamic Binding
In dynamic binding, the code to be executed in response to the function call is decided at runtime.
C++ has virtual functions to support this. Because dynamic binding is flexible, it avoids the
drawbacks of static binding, which connected the function call and definition at build time.
Message Passing
Objects communicate with one another by sending and receiving information. A message for an
object is a request for the 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.
Features of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Dynamic Binding
8. Message Passing
Benefits of OOP:-
We can build the programs from standard working modules that communicate with one another,
rather than having to start writing the code from scratch which leads to saving of development
time and higher productivity,
OOP language allows breaking the program into the bit-sized problems that can be solved
easily (one object at a time).
The new technology promises greater programmer productivity, better quality of software and
lesser maintenance cost.
OOP systems can be easily upgraded from small to large systems.
It is possible that multiple instances of objects co-exist without any interference,
It is very easy to partition the work in a project based on objects.
It is possible to map the objects in problem domain to those in the program.
The principle of data hiding helps the programmer to build secure programs which cannot be
invaded by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing classes.
Message passing techniques is used for communication between objects which makes the
interface descriptions with external systems much simpler.
The data-centered design approach enables us to capture more details of model in an
implementable form.
C++ Data Types
In C++, data types are declarations for variables. This determines the type and size of data associated
with variables.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
1. Primary or Built-in or Fundamental data type
These data types are built-in or predefined data types and can be used directly by the user to declare
variables.
Datatype Modifiers
As the name suggests, datatype modifiers are used with built-in data types to modify the length of
data that a particular data type can hold.
Data type modifiers available in C++ are:
Signed
Unsigned
Short
Long
The below table summarizes the modified size and range of built-in datatypes when combined with
the type modifiers:
Data Type Size (in bytes) Range
Mrs. P.D.Titavekar
Object Oriented Programming using C++
2. Derived Data Types
The data-types that are derived from the primitive or built-in datatypes are referred to as Derived
Data Types. These can be of four types namely:
Function
Array
Pointers
References
Int sum;
sum =a+b;
2. Array: An array is a collection of items stored at continuous memory locations. The idea of
array is to represent many instances in one variable.
Syntax:
DataType ArrayName[size];
Ex:- int a[10];
3. Pointers: Pointers are symbolic representation of addresses. They enable programs to simulate
call-by-reference as well as to create and manipulate dynamic data structures. It‘s general
declaration in C/C++ has the format:
Syntax:
datatype *ptr_name;
Example:
int *p;
4. Reference: When a variable is declared as reference, it becomes an alternative name for an
existing variable. A variable can be declared as reference by putting ‗&‘ in the declaration.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
3. User-Defined DataTypes:
The data types that are defined by the user are called the derived datatype or user-defined derived
data type.
These types include:
Class
Structure
Union
Enumeration
Typedef defined DataType
Below is the detailed description of the following types:
1. 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.
Syntax:
Example:
Class College
{
Public:
Char name[10]=‖nckbca‖;
Void display()
{
Cout<<‖College name is ‖<<name;
}
}
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.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
Union: Like Structures, union is a user defined data type. In union, all members share the same
memory location.
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:
// of enum in C++
#include <iostream>
Tue,
Wed,
Thur,
Fri,
Sat,
Sun };
int main()
day = Wed;
Mrs. P.D.Titavekar
Object Oriented Programming using C++
return 0;
Output:
2
Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for an
existing type. This can increase the portability(the ability of a program to be used across
different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed. Using typedef one
can also aid in self-documenting code by allowing descriptive names for the standard data
types.
Syntax:
typedef datatype name;
Keywords
Keywords(also known as reserved words) have special meanings to the C++ compiler and are
always written or typed in short(lower) cases. Keywords are words that the language uses for a
special purpose, such as void, int, public, etc. It can‘t be used for a variable name or function name
or any other identifiers. The total count of reserved keywords is 95. Below is the table for some
commonly used C++ keywords.
C++ Keyword
Mrs. P.D.Titavekar
Object Oriented Programming using C++
C++ Keyword
Operators in C++ :-
An operator is a symbol that operates on a value to perform specific mathematical or logical
computations. They form the foundation of any programming language.
Operators in C++ can be classified into 6 types:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Ternary or Conditional Operators
1) Arithmetic Operators
Mrs. P.D.Titavekar
Object Oriented Programming using C++
int a = 5;
Increases the integer value of the variable by
Increment Operator ++ a++; // returns
one
6
int a = 5;
Decrement Decreases the integer value of the variable by
—
Operator one a–; // returns 4
B) Binary Operators: These operators operate or work with two operands. For example:
Addition(+), Subtraction(-), etc.
Name Symbol Description Example
int a = 3, b = 6;
Addition + Adds two operands
int c = a+b; // c = 9
int a = 9, b = 6;
Subtraction – Subtracts second operand from the first
int c = a-b; // c = 3
int a = 3, b = 6;
Multiplication * Multiplies two operands
int c = a*b; // c = 18
int a = 12, b = 6;
Division / Divides first operand by the second operand
int c = a/b; // c = 2
int a = 8, b = 6;
Modulo Operation % Returns the remainder an integer division
int c = a%b; // c = 2
2) Relational Operators
int a = 3, b
= 6;
Is Equal To == Checks if both operands are equal a==b;
// returns
false
Mrs. P.D.Titavekar
Object Oriented Programming using C++
a>b;
// returns
false
int a = 3, b
= 6;
Greater Than or Checks if first operand is greater than or equal to a>=b;
>=
Equal To the second operand
// returns
false
int a = 3, b
= 6;
Checks if first operand is lesser than the second a<b;
Less Than <
operand
// returns
true
int a = 3, b
= 6;
Less Than or Equal Checks if first operand is lesser than or equal to a<=b;
<=
To the second operand
// returns
true
int a = 3, b
= 6;
Not Equal To != Checks if both operands are not equal a!=b;
// returns
true
3) Logical Operators
These operators are used to combine two or more conditions or constraints or to complement the
evaluation of the original condition in consideration. The result returns a Boolean value,
i.e., true or false.
Name Symbol Description Example
int a = 3, b =
Logical Returns true only if all the operands are true or non- 6;
&&
AND zero a&&b;
// returns true
Mrs. P.D.Titavekar
Object Oriented Programming using C++
int a = 3, b =
Returns true if either of the operands is true or non- 6;
Logical OR ||
zero a||b;
// returns true
int a = 3;
Logical NOT ! Returns true if the operand is false or zero !a;
// returns false
4) Bitwise Operators
These operators are used to perform bit-level operations on the operands. The operators are first
converted to bit-level and then the calculation is performed on the operands. Mathematical
operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for
faster processing.
int a = 2, b =
Copies a bit to the evaluated result if it exists in both 3;
Binary AND &
operands (a & b);
//returns 2
int a = 2, b =
Copies a bit to the evaluated result if it exists in any 3;
Binary OR |
of the operand (a | b);
//returns 3
int a = 2, b =
Copies the bit to the evaluated result if it is present 3;
Binary XOR ^
in either of the operands but not both (a ^ b);
//returns 1
int a = 2, b =
Shifts the value to left by the number of bits 3;
Left Shift <<
specified by the right operand. (a << 1);
//returns 4
Mrs. P.D.Titavekar
Object Oriented Programming using C++
int a = 2, b =
Shifts the value to right by the number of bits 3;
Right Shift >>
specified by the right operand. (a >> 1);
//returns 1
int b = 3;
One‘s
~ Changes binary digits 1 to 0 and 0 to 1
Complement (~b); //returns
-4
5) Assignment Operators
These operators are used to assign value to a variable. The left side operand of the assignment
operator is a variable and the right side operand of the assignment operator is a value. The value on
the right side must be of the same data type as the variable on the left side otherwise the compiler
will raise an error.
Assignment Assigns the value on the right to the variable on the int a = 2;
Operator = left // a = 2
Add and First adds the current value of the variable on left to int a = 2,
b = 4;
Assignment += the value on the right and then assigns the result to
Operator the variable on the left a+=b; // a
=6
Subtract and First subtracts the value on the right from the int a = 2,
- b = 4;
Assignment current value of the variable on left and then assign
Operator = the result to the variable on the left a-=b; // a
= -2
Multiply and First multiplies the current value of the variable on int a = 2,
b = 4;
Assignment *= left to the value on the right and then assign the
Operator result to the variable on the left a*=b; // a
=8
Divide and First divides the current value of the variable on left int a = 4,
b = 2;
Assignment /= by the value on the right and then assign the result
Operator to the variable on the left a /=b; // a
=2
Mrs. P.D.Titavekar
Object Oriented Programming using C++
6) Ternary or Conditional Operators(?:)
#include <iostream>
void logical();
void scope_resolution();
int main() {
int a, b;
a = 7;
b = 2;
//Arithmatic Operators
arithmetic(a,b);
a = 10;
b = 100;
incdec(a,b);
Mrs. P.D.Titavekar
Object Oriented Programming using C++
//Assignment operator
a = 2;
b = 7;
assign(a,b);
//Relational Operators
a = 3;
b = 5;
relational(a,b);
//Logical Operators
logical();
scope_resolution();
return 0;
Mrs. P.D.Titavekar
Object Oriented Programming using C++
// printing the division of a by b
n1 += n2; // a = a +b
Mrs. P.D.Titavekar
Object Oriented Programming using C++
cout <<"a = "<< n1 << endl;
bool result;
void logical()
bool result;
Mrs. P.D.Titavekar
Object Oriented Programming using C++
void scope_resolution()
Mrs. P.D.Titavekar
Object Oriented Programming using C++
{
int k=m;
cout<<"k= "<<k<<"\n";
cout<<"m= "<<m<<"\n";
cout<<"::m= "<<::m<<"\n";
cout<<"m= "<<m<<"\n";
cout<<"::m= "<<::m<<"\n";
C++ is a programming language from a high level that is widely used for creating applications and
software. One of the most important concepts in C++ programming is Flow Control, which refers to
the ability to direct the flow of a program based on specific conditions. This allows developers to
control how their programs execute and can help to make them more efficient and effective. In this
article, we will see the different types of flow control available in C++, how they work, and when
they are most appropriate.
Conditional Statements:
Conditional Statements are used in C++ to run a certain piece of program only if a specific condition
is met. There are generally three types of conditional statements in C++: if, if-else, and switch.
if Statement:
Mrs. P.D.Titavekar
Object Oriented Programming using C++
The if statement is the simplest of the three and is used to run a certain piece of code nly if a certain
condition is true. For example:
int x = 5;
if (x == 5) {
std::cout << "x is 5" << std::endl;
}
In this example, the block of code inside the curly braces will only be executed if the condition inside
the parentheses is true.
if-else Statement:
The if-else statement is used when we want to execute some code only if some condition exists. If the
given condition is true then code will be executed otherwise else statement will be used to run other
part of the code.For example:
C++ Code:
1. int x = 5;
2. if (x == 5) {
3. std::cout << "x is 5" << std::endl;
4. } else {
5. std::cout << "x is not 5" << std::endl;
6. }
In this example, if the condition inside the parentheses is true, the first block of code will be executed.
Otherwise, the second block of code will be executed.
switch Statement:
The switch statement is used to execute different blocks of code based on the value of a variable. For
example:
1. switch (variable) {
2. case value1:
3. // code to execute if the variable is equal to value1
4. break;
5. case value2:
6. // code to execute if the variable is equal to value2
7. break;
8. // add more cases as needed
9. default:
Mrs. P.D.Titavekar
Object Oriented Programming using C++
10. // code to execute if the variable does not match any case
11. }
C++ code:
1. int x = 2;
2. switch (x) {
3. case 1:
4. std::cout << "x is 1" << std::endl;
5. break;
6. case 2:
7. std::cout << "x is 2" << std::endl;
8. break;
9. default:
10. std::cout << "x is not 1 or 2" << std::endl;
11. break;
12. }
In this example, the switch statement will execute the block of code associated with the value of x. If
x is 1, the first block of code will be executed. If x is 2, the second block of code will be executed. If x
is any other value, the default block of code will be executed.
Loops:
Loops are used in C++ to execute a block of code multiple times, either until a certain condition is
met or for a specific number of times. There are generally three types of loops in C++: while, do-
while, and for.
While Loop:
The while loop is used to execute when we want to run some code for until some specific condition
matches. For example:
C++ Code:
1. int x = 0;
2. while (x < 5) {
3. std::cout << x << std::endl;
4. x++;
5. }
In this example, the while loop will continue to execute the block of code inside the curly braces as
long as x is less than 5. Each time the loop executes, the value of x will be incremented by 1.
Mrs. P.D.Titavekar
Object Oriented Programming using C++
do-while Loop:
The do-while loop is the same as the while loop, but the condition is checked after the first iteration
of the loop. For example:
C++ Code:
1. int x = 0;
2. do {
3. std::cout << x << std::endl;
4. x++;
5. } while (x < 5);
In this example, the do-while loop will execute the block of code inside the curly brackets, and then it
will check the condition. So it will be executed a minimum of one time.
for Loop:
The for loop allows a program to execute a piece of program a fixed number of times. The syntax for
the for loop is:
Pseudo Code:
Here is an example that uses the for loop to print the numbers from 1 to 10:
C++ Code:
Mrs. P.D.Titavekar