01 Oop

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Introduction to object oriented programming languages

• A program is a set of instructions that help computer to perform tasks.


• The languages that are used to write a program or set of instructions are called "Programming languages".
Programming languages are broadly categorized into three types −
• Machine level language
• Assembly level language
• High-level language
• Machine level Language: Machine language is lowest level of programming language. It handles binary data
i.e. 0’s and 1’s. It directly interacts with system. Machine language is difficult for human beings to understand
as it comprises combination of 0’s and 1’s.
• Assembly level language : Assembly language is a middle-level language. It consists of a set of instructions
in a specific format called commands. It uses symbols to represent field of instructions. It is very close to
machine level language. The computer should have assembler to translate assembly level program to machine
level program.
• High-level Language: High-level language uses format or language that is most familiar to users. The
instructions in this language are called codes or scripts. The computer needs a compiler and interpreter to
convert high-level language program to machine level language.
• A high level language can be further categorized into object oriented and procedural programming
language.
Procedure-Oriented Programming
• C, Pascal, Fortran, and similar languages are procedural languages.
• Each statement in the language tells the computer to do something:
• Get some input
• Add these numbers
• Divide by 6
• Display that output
• A program in a procedural language is a list of instructions.
Contd…
• Division into functions:
• Procedural program is divided into functions.
• Each function has a clearly defined purpose and a clearly defined interface to the other functions in the
program.
• The idea of breaking a program into functions can be further extended by grouping a number of
functions together into a larger entity called a module.
Contd….
• In multi-function program important data items are placed as global so that they may be accessed
by all functions.
• Each function may have its own local data.
Contd….
• Drawbacks of procedural programming language:
• Since every function has complete access to the global variables, the new programmer can corrupt the
data accidentally by creating function.
• We can access the data of one function from other since, there is no protection.
• In large program it is very difficult to identify what data is used by which function.
• Similarly, if new data is to be added, all the function needed to be modified to access the data.
• Does not model real world problem very well.
• Characteristics
• Emphasis is on doing things (algorithms).
• Large programs are divided into smaller programs known as functions.
• Most of the functions share global data.
• Data move openly around the system from function to function.
• Functions transform data from one form to another.
• Employs top-down approach in program design,
• Top down approach
• Top down decomposition is the process of breaking the overall procedure or task into component parts
(modules) and then subdivide each component module until the lowest level of details has been reached.
• Example: The payroll system of a company can contain the following modules or tasks
• Master file
• Earnings
• Deductions
• Taxing
• Net earning
• Print reports
Object oriented Programming (OOP)
• OOP was introduced to overcome flaws in the procedural approach to
programming.
• Such as lack of reusability and maintainability.
• Fundamental idea behind object-oriented languages is to combine into single unit
both data and the functions that operate on that data.
• Such a unit is called an object.
• In OOP, problem is divided into the number of entities called objects and then builds data and functions
around these objects.
• It ties the data more closely to the functions that operate on it , and protects it from accidental modification
from the outside functions.
• Data of an object can be accessed only by the functions associated with that object.
• Communication of the objects done through function.
• Follows bottom up design program design.
• Bottom up approach
• Reverse top-down approach.
• Lower level tasks are first carried out and are then integrated to provide the solution of a single program.
• Lower level structures of the program are evolved first then higher level structures are created.
• It promotes code reuse.
• It may allow unit testing.
• OOP is said to be the most popular programming model among developers. It is well suited for programs that
are large, complex, and actively updated or maintained.
• It makes the development and maintenance of software easy by providing major concepts such as abstraction,
inheritance, polymorphism, and encapsulation. These four are also the four pillars of an object-oriented
programming system.
• OOPs, provide the ability to simulate real-world events much more effectively.
• We can provide the solution to real-world problems if we are using the Object-Oriented Programming
language. OOPs, provide data hiding, whereas, in Procedure-oriented programming language, global data can
be accessed from anywhere.
• The examples of OOPs are - C#, Python, C++, Java, PHP, Scala, Perl, etc.
C ++

• C++ is the most used and most popular programming language developed by Bjarne Stroustrup at
AT & T Bell in 1980’s.
• C++ is the combination of simula67 and C languages.
• Initially it is called as the C with classes and later it is renamed as C++.
• C++ is a high-level and object-oriented programming language. This language allows developers
to write clean and efficient code for large applications and software development, game
development, and operating system programming.
• It is an expansion of the C programming language to include Object Oriented Programming(OOPs)
and is used to develop programs for computers.
Basic Object-Oriented Programming (OOPS) Concept in C++
• There are some basic concepts that act as the building blocks of OOPs.
• Classes & Objects
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Class and objects :
• An Object can be defined as an entity that has a state and behavior, or in other words, anything
that exists physically in the world is called an object. It can represent a dog, a car, a person, a
table, etc. An object means a combination of data and programs, which further represent an
entity.
• Class: It is a collection of object.
• Class is a structure where we can defines variables and methods to utilize by objects.
• Class can be defined as a blueprint of the object. It is basically a collection of objects which
act as building blocks.
• For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, the Car is the class.

• Without class object doesn’t exist.


• Abstraction :
• Data abstraction is one of the most essential and important features of object-oriented
programming in C++.
• 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
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.
• Encapsulation:
• Encapsulation in C++ is defined as the wrapping up of data and information in a single unit. In Object
Oriented Programming, Encapsulation is defined as binding together the data and the functions that
manipulate them.
• It is also known as information hiding concept.
• The data is not accessible to the outside world and only those function which are wrapped in the class can
access it.
• Consider a real-life example of encapsulation, in a company, there are different sections like the accounts
section, finance section, sales section, etc. Now,
• The finance section handles all the financial transactions and keeps records of all the data related to finance.
• Similarly, the sales section handles all the sales-related activities and keeps records of all the sales.
• Now there may arise a situation when for some reason an official from the finance section needs all the data
about sales in a particular month.
• In this case, he is not allowed to directly access the data of the sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular data.
• Polymorphism: The term "Polymorphism" is the combination of "poly" + "morphs" which means many
forms.

• More than one function with the same name but different working.
Types of polymorphism:
1. Compile time polymorphism : This type of polymorphism is achieved by function overloading or operator
overloading. Memory will be allocated at compile time.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the functions are said to
be overloaded, hence this is known as Function Overloading. Functions can be overloaded by changing the
number of arguments or/and changing the type of arguments. In simple terms, it is a feature of object-
oriented programming providing many functions that have the same name but distinct parameters when
numerous tasks are listed under one function name.
B. Operator Overloading: It is a specific case of polymorphism, where different operators have different
implementations depending on their arguments.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic polymorphism are
other names for runtime polymorphism. The function call is resolved at runtime in runtime polymorphism.
Overriding is a run time polymorphism where more than one method is having the same name, number of
parameters and the type of the parameters.
• Virtual function : A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late
binding where the compiler matches the object with the right called function and executes it during the
runtime. This technique falls under Runtime Polymorphism.
• Inheritance : It is mechanism of deriving a new class from an existing
class. Five types of inheritance are:
1. Single level
2. Multi level
3. Multiple
4. Hierarchical
5. Hybrid
• Single level : In single inheritance, a class is allowed to inherit from only one class. i.e. one
subclass is inherited by one base class only.
• Multi level inheritance:
• In this type of inheritance, a derived class is created from another derived class.
Multiple Inheritance : Multiple Inheritance is a feature of C++ where a class can inherit from more than one
class. i.e one subclass is inherited from more than one base class.
• Hierarchical inheritance : In this type of inheritance, more than one subclass is inherited from a
single base class. i.e. more than one derived class is created from a single base class.

• Hybrid inheritance: Hybrid Inheritance is implemented by combining more than one type of
inheritance.
Basic structures of a C++ Program

Documentation Section

Preprocessor directives

Class declaration

Member function definition

Main function
1. Document section:
• It can be also called as comment section.
• Whatever written in the documentation section is the comment and is not compiled by the compiler.
• Documentation Section is optional since the program can execute without them.
• C++ supports two comment styles: single line comment and multiline comment. Single line comments are
used to define line-by-line descriptions. Double slash (//) is used to represent single line comments.
• / / single line comment
• Multiline comments are used to define multiple lines descriptions and are represented as / * * /. For example,
consider this statement.
• /* An example to demonstrate multiline comment */
• Preprocessor directives
• The statement which are executed before compilation are known as preprocessor
directives. There are two types of preprocessor directives.
1. Header file: collection of library function
2. Macro : mainly used to defined symbolic constant
• Class declaration :
• Class is collection of object.
• Class mainly contain variables and function.
• Variable which is define inside a class is called as the member variable and function which are define inside a
class is called as the member function.
• So class is a collection of member variable and member function.
class classname
{
member variable
member function
};
• Member function definition:
• Here we can define member function in two ways, inside the class or outside the class.
• If a member function is defined inside a class then there is no need of function declaration while if a member
function is defined outside the class then the corresponding function should declare inside a class.
• Main function:
• Like C program, C++ is also a collection function.
• Any C++ program must contain at least one function that is the main function.
• The execution of any C++ program must start from the main function and the entire program will
be executed.
C++ std Namespace
• In C++, a namespace is a collection of related names or identifiers (functions, class, variables)
which helps to separate these identifiers from similar identifiers in other namespaces or the global
namespace.
• The identifiers of the C++ standard library are defined in a namespace called std.
• In order to use any identifier belonging to the standard library, we need to specify that it belongs to
the std namespace. One way to do this is by using the scope resolution operator ::. For example,

• std::cout << "Hello World!";


• Here, we have used the code std:: before cout. This tells the C++ compiler that the cout object we
are using belongs to the std namespace.
Example
• std Namespace With using Declaration
• We can bring selected identifiers to the current scope with the help of the using declaration. To do this, we
utilize the using keyword.
• By doing this, we won't need to prefix the specified identifiers with std::. For example,
• std Namespace With using Directive
• We can use the using directive to bring all the identifiers of the namespace std as if they were declared
globally. To do this, we utilize the using keyword.
• By doing this, we can:
1. avoid using the std:: prefix
2. avoid utilizing the using declaration repeatedly
Tokens in C++

• C++ has the following tokens:


• Keywords
• Identifiers
• Constant
• Strings
• Operators
Keywords in C++
• 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.
• asm: To declare that a block of code is to be passed to the assembler.
• auto: A storage class specifier that is used to define objects in a block.
• break: Terminates a switch statement or a loop.
• case: Used specifically within a switch statement to specify a match for the statement’s expression.
• catch: Specifies actions taken when an exception occurs.
• char: Fundamental data type that defines character objects.
• class: To declare a user-defined type that encapsulates data members and operations or member
functions.
• const: To define objects whose value will not alter throughout the lifetime of program execution.
• continue:- Transfers control to the start of a loop.
• default:- Handles expression values in a switch statement that are not handled by case.
• delete: Memory deallocation operator.
• do: indicate the start of a do-while statement in which the sub-statement is executed repeatedly
until the value of the expression is logical-false.
• double: Fundamental data type used to define a floating-point number.
• else: Used specifically in an if-else statement.
• enum: To declare a user-defined enumeration data type.
• extern: An identifier specified as an extern has an external linkage to the block.
• float:- Fundamental data type used to define a floating-point number.
• for: Indicates the start of a statement to achieve repetitive control.
• friend: A class or operation whose implementation can access the private data members of a class.
• goto: Transfer control to a specified label.
• if: Indicate the start of an if statement to achieve selective control.
• inline: A function specifier that indicates to the compiler that inline substitution of the function body is to be
preferred to the usual function call implementation.
• int: Fundamental data type used to define integer objects.
• long: A data type modifier that defines a 32-bit int or an extended double.
• new: Memory allocation operator.
• operator: Overloads a c++ operator with a new declaration.
• private: Declares class members which are not visible outside the class.
• protected: Declares class members which are private except to derived classes
• public: Declares class members who are visible outside the class.
• register: A storage class specifier that is an auto specifier, but which also indicates to the compiler that an
object will be frequently used and should therefore be kept in a register.
• return: Returns an object to a function’s caller.
• short: A data type modifier that defines a 16-bit int number.
• signed: A data type modifier that indicates an object’s sign is to be stored in the high-order bit.
• sizeof: Returns the size of an object in bytes.
• static: The lifetime of an object-defined static exists throughout the lifetime of program execution.
• struct: To declare new types that encapsulate both data and member functions.
• switch: This keyword is used in the “Switch statement”.
• template: parameterized or generic type.
• this: A class pointer points to an object or instance of the class.
• throw: Generate an exception.
• try: Indicates the start of a block of exception handlers.
• typedef: Synonym for another integral or user-defined type.
• union: Similar to a structure, struct, in that it can hold different types of data, but a union can hold only one of
its members at a given time.
• unsigned: A data type modifier that indicates the high-order bit is to be used for an object.
• virtual: A function specifier that declares a member function of a class that will be redefined by a derived
class.
• void: Absent of a type or function parameter list.
• volatile: Define an object which may vary in value in a way that is undetectable to the compiler.
• while: Start of a while statement and end of a do-while statement.
C++ Data Types
• While writing program in any language, you need to use various variables to store various information.
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory. A data type specifies the type of data that a variable can store
such as integer, floating, character etc.
• There are 4 types of data types in C++ language.

Types Data Types


Basic Data Type int, char, float, double, etc
Derived Data Type array, pointer, etc
Enumeration Data Type enum
User Defined Data Type structure
Basic Data Types
• The basic data types are integer-based and floating-point based. C++ language supports both signed and
unsigned literals.
• The memory size of basic data types may change according to 32 or 64 bit operating system.
• Let's see the basic data types. It size is given according to 32 bit OS.
Data Type Memory Size Typical Range
char 1byte -127 to 127 or 0 to 255

unsigned char 1byte 0 to 255


signed char 1byte -127 to 127
int 4bytes -2147483648 to 2147483647

unsigned int 4bytes 0 to 4294967295


signed int 4bytes -2147483648 to 2147483647

short int 2bytes -32768 to 32767


unsigned short int 2bytes 0 to 65,535
signed short int 2bytes -32768 to 32767
long int 8bytes -9223372036854775808 to
9223372036854775807

signed long int 8bytes same as long int


unsigned long int 8bytes 0 to 18446744073709551615

long long int 8bytes -(2^63) to (2^63)-1

unsigned long long int 8bytes 0 to 18,446,744,073,709,551,615

float 4bytes
double 8bytes
long double 12bytes
wchar_t 2 or 4 bytes 1 wide character
• The size of variables might be different from those shown in the above table, depending on the compiler and
the computer you are using.
• Following is the example, which will produce correct size of various data types on your computer.
Enumerated Data Type
• Enumerated Types :
• An enumeration is a user-defined data type that consists of integral constants.
• Enum is a collection of named integer constant means it’s each element is assigned by integer value.
• To define an enumeration, keyword enum is used.
• The general form of an enumeration type is −
• enum enum-name { list of names } var-list;
• Here, the enum-name is the enumeration's type name. The list of names is comma separated.
• For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is
assigned the value "blue".
• enum color { red, green, blue } c;
• c = blue;
• By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But
you can give a name, a specific value by adding an initializer.
• enum season { spring, summer, autumn, winter };
• Here, the name of the enumeration is season.
• And, spring, summer and winter are values of type season.
• By default, spring is 0, summer is 1 and so on. You can change the default value of an enum element during declaration (if
necessary).
enum season
{ spring = 0,
summer = 4,
autumn = 8,
winter = 12
};
Exercise
Exercise
Contd.

You might also like