Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Introduction To OOPS and C++

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 48

UNIT-I

Introduction to Object Oriented Programming,


Structure of C++ program, Tokens, Keywords,
Identifiers and Constants, Basic Data Types,
Operators and Type Conversions.

Functions: Returning values from functions.


Reference arguments, Overloaded function, Inline
function, Default arguments, return by reference.
Procedue vs OOP(1 of 7)
Procedure Oriented Programming
Program is divided into functions, every function has its own data and global
data.
Main program Global data Global data

Function-1 Function-2 Function-3

Function-4 Function-5
Function-1 Function-2 Function-3

Local data Local data Local data


Function-6 Function-7 Function-8

Relationship of Data & Functions in


Structure of procedure-oriented programs Procedural Programming
2
Procedure vs OOP(2 of 7)

Object Oriented Programming (OOP)


OOP decompose the problem into number of entities called objects and it
contains the data and functions.
Object A Object B

Data Data
Communication
Methods Methods

Object C
Methods

Data

Organization of Data & Methods in


OOP
3
Procedure vs OOP(3 of 7)
Procedure Vs Object Oriented Programming
Characteristics of Structure-Oriented Programming
• Emphasis is on doing things.
• 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
Procedure vs OOP(4 of 7)
Characteristics of Object-Oriented
Programming
• Emphasis is on data rather than procedure.
• Programs are divided into objects.
• Functions that operate on the data of an object are tied together in
the data structure.
• Data is hidden and cannot be accessed by external functions.
• Objects may communicate with each other through functions.
• Employs bottom-up approach in program design
• New data and functions can be easily added whenever necessary.
Procedure vs OOP(5 of 7)
Top Down Vs Bottom Up Approach

 Top Down approach:


– A Single module will be split into several smaller modules
– General to Specific

 Bottom Up approach:
– Lot of small modules will be grouped to form a single large
module
– Specific to General

• If the requirements are clear at the first instance, we can go for Top
Down approach.

• In circumstances where the requirements may keep on adding, then


we can go for Bottom Up approach.
Procedure vs OOP(6 of 7)
Benefits of OOP

• Through inheritance, we can eliminate redundant code and extend


the use of existing classes.
• The principle of data hiding helps the programmer to build secure
programs that cannot be invaded by code in the parts of the
program.
• It is easy to partition the work in a project based on objects.
• Object oriented system easily upgraded from small to large
systems.
• Software complexity can be easily managed.
Procedure vs OOP(7 of 7)
Applications of OOP
• Real-time systems.
• Object-Oriented Databases.
• Neural Networks and Parallel Programming.
• Decision Support and Office Automation Systems.
Introduction to OOP(Object Oriented
Programming) (1 of 7)
Object Oriented Programming Concepts:

• Classes

• Objects

• Data Abstraction

• Encapsulation

• Inheritance

• Polymorphism
Introduction to OOP(2 of 7)
Class & Object:

 A class is a collection of instance variables and methods.


 Ex: fruit mango;

 class object
 For example, mango, apple and orange are members of the class
fruit.

 A class is a template or logical structure.

 Classes are user-defined data types and behave like the built-in
types of a programming language.

 Objects are instances of the type class.

 Objects are the basic run-time entities in an object-oriented system.


Introduction to OOP(3 of 7)

Data Abstraction
• Abstraction refers to the act of representing essential
features without including the background details or
explanations.
• Abstraction are of two types:
• Procedure Abstraction
• Data Abstraction
• The access specifiers in JAVA or any OOP language,
provides data abstraction.
Introduction to OOP(4 of 7)

Encapsulation

• The wrapping up of data and methods into a single unit ( called

class) is known as encapsulation.

• That is, the data and methods are given in the class definition.

• Data encapsulation is the most striking features of a class.


Introduction to OOP(5 of 7)
Inheritance
• Inheritance is the process by which objects of one class acquire the

properties of another class. The concept of inheritance provides the

reusability.

• A class can inherit one or more classes. Inherited class is called as

parent class or super class. Class that inherits a parent class is called

as child class or sub class.


Introduction to OOP(6 of 7)
Benefits of Inheritance
1) Software reusability (among projects
2) Code sharing (within a project)
3) Increased reliability (resulting from reuse and sharing of well-
tested code)
4) Consistency of interface (among related objects)
5) Rapid prototyping (quickly assemble from pre-existing
components)
6) Polymorphism and frameworks (high-level reusable components)
7) Information hiding
Introduction to OOP(7 of 7)
Polymorphism

Poly – Many Morph – Form

 Polymorphism is the characteristic feature, that enables an entity to


co-exist in more than one form.

 Ex: It allows the single method to perform different actions based on


the parameters.
History of C++
 C++ programming language was developed in 1980 by Bjarne
Stroustrup at bell laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
 Bjarne Stroustrup is known as the founder of C++ language.
 It was develop for adding a feature of OOP (Object Oriented
Programming) in C without significantly changing the C
component.
 C++ programming is "relative" (called a superset) of C, it means
any valid C program is also a valid C++ program.
Structure of C++ program
1. Documentation Section
2. Preprocessor Directives or Compiler Directives Section
(i) Link Section
(ii) Definition Section
3. Global Declaration Section
4. Class declaration or definition
5. Main C++ program function called main ( )
6. Beginning of the program: Left brace {
(i) Object declaration part;
(ii) Accessing member functions (using dot operator);
7. End of the main program: Right brace}
C++ Basic io
 C++ I/O operation is using the stream concept. Stream is the sequence of
bytes or flow of data. It makes the performance fast.
 If bytes flow from main memory to device like printer, display screen, or a
network connection, etc, this is called as output operation.
 If bytes flow from device like printer, display screen, or a network
connection, etc to main memory, this is called as input operation.
 Let us see the common header files used in C++ programming are:
<iostream>: It is used to define the cout, cin and cerr objects, which
correspond to standard output stream, standard input stream and standard
error stream, respectively.
<fstream>: It is used to declare services for user-controlled file processing.

Refer Example program simpleprog.cpp


Tokens
A token is the smallest element of a program that is meaningful to the
compiler. Tokens can be classified as follows:
 Keywords
 Identifiers
 Constants
 Strings
 Special Symbols
 Operators
Keywords
 Keyword: Keywords are pre-defined or reserved words in a programming
language
 asm auto bool break case
catch char class const_cast continue
default delete do double else
enum dynamic_case extern false float
for union unsigned using friend
goto if inline int long
mutable virtual namespace new operator
private protected public register void
reinterpret_cast return short signed sizeof
static static_cast volatile struct switch
template this throw true try
typedef typeid unsigned wchar_t while
Identifiers
 Identifiers: Identifiers are used as the general terminology for
naming of var

There are certain rules that should be followed while naming


identifiers:

 They must begin with a letter or underscore(_).


 They must consist of only letters, digits, or underscore. No other
special character is allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only first 31 characters are
significant.
 iables, functions and arrays.
Constants(1 of 2)
 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.
const data_type variable_name;
(or)
const data_type *variable_name;
Constants(2 of 2)
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”
Strings
Strings:
Strings are nothing but an array of characters ended with a null
character (‘\0’).This null character indicates the end of the string.

 char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’,
‘s’, ‘\0’};
 char string[20] = “geeksforgeeks”;
 char string [] = “geeksforgeeks”;

Refer Example program stringex.cpp


Special Symbols
Special Symbols:
The following special symbols are used in C having some special
meaning and thus, cannot be used for some other purpose.
[] () {}, ; * =, #
Operators(1 of 9)
Operators:
Operators are symbols that triggers an action when applied to
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
Operators(2 of 9)
 Binary Operators: Those operators that require two operands to
act upon are called binary operators. Binary operators are
classified into :
◦ Arithmetic operators
◦ Relational Operators
◦ Logical Operators
◦ Assignment Operators
◦ Conditional Operators
◦ Bitwise Operators

 Ternary Operators: These operators requires three operands to act


upon. For Example Conditional operator(?:).
Operators(3 of 9)
 Unary Opertors:

Operator Description
++ Increment
-- Decrement
sizeof returns the size of a variable
, causes a sequence of operations to
be performed.
. (dot) and -> (arrow) are used to reference individual
members of classes, structures,
and unions.
& returns the address of a variable.
Operators(4 of 9)
Binary Operators:
 Arithmetic Operators:

Operator Result

+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
Operators(5 of 9)
 Relational Operators:
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Operators(6 of 9)
 Logical Operators:

Operator Result
|| Logical OR
&& Logical AND
! Logical unary NOT
Operators(7 of 9)
 Assignment Operators:
Operator Result
= assigns value from right opearnad to left operand
+= short hand addition assignment opeartor
-= short hand subtraction assignment opeartor
*= short hand multiplication assignment opeartor
/= short hand division assignment opeartor
%= short hand modulo assignment opeartor
Operators(8 of 9)
 Conditional Operator or ternary Opeartor:

Condition ? X : Y

If Condition is true then it returns value of X otherwise returns value


of Y.
Operators(9 of 9)
 Bitwise Operators:
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
>> Right shift
<< Left shift
Basic Data types(1 of 3)
Premetive built-in types:

Type Keyword
Boolean bool
Character char
Integer int
Floating point float
Double floating point double
Valueless void
Basic Data types(2 of 3)
Several of the basic types can be modified using one or more of
these type modifiers −

 signed
 unsigned
 short
 long
Basic Data types(3 of 3)
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.
Type Typical Bit Width 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 4bytes -2,147,483,648 to 2,147,483,647
signed long int 4bytes same as long int
unsigned long int 4bytes 0 to 4,294,967,295
float 4bytes +/- 3.4e +/- 38 (~7 digits)
double 8bytes +/- 1.7e +/- 308 (~15 digits)
long double 8bytes +/- 1.7e +/- 308 (~15 digits)
Type Conversion
Converting from one type to other type is called type conversion
 Implicit conversion: Implicit conversions are automatically performed
when a value is copied to a compatible type
Example:
short a=2000;
int b;
b=a;
 Type casting(Explicit conversion):If imlicit is not possible we need to
write a casting statement
Example:
double x = 10.3;
int y;
y = (int) x; // cast notation
Refer Example program typecast.cpp
Returning values from functions(1 of 4)
return statement:
 The return statement stops execution and returns to the calling function.
 When a return statement is executed, the function is terminated immediately
at that point, regardless of whether it's in the middle of a loop, etc.

1. return optional in void functions:


 A void function doesn't have to have a return statement -- when the end is
reached, it automatically returns. However, a void function may optionally
contain one or more return statements.
Returning values from functions(2 of 4)
void printChars(char c, int count)
{
for (int i=0; i<count; i++)
{
cout << c;
}//end for
return; // Optional because it's a void function
} //end printChars
Returning values from functions(3 of 4)
2. return required in non-void functions
 If a function returns a value, it must have a return statement that specifies the
value to return.
 It's possible to have more than one return, but the (human) complexity of a
function generally increases with more return statements.
 It's generally considered better style to have one return at the end, unless that
increases the complexity.
Returning values from functions(4 of 4)
int max(int a, int b)
{
int maxval;
if (a > b)
{
maxval = a;
}
else
{
maxval = b;
}
return maxval;
}//end max
Reference arguments(1 of 2)
 There are two ways to pass value or data to function in C++
language: call by value and call by reference.

Original value

yes
No
modified

Call by
Call by value
reference
Reference arguments(2 of 2)
 Call by value
 In call by value, value being passed to the function is locally stored by the
function parameter in stack memory location.
 If you change the value of function parameter, it is changed for the current
function only.
 It will not change the value of variable inside the caller method such as
main().
 Call by reference
 In call by reference, original value is modified because we pass reference
(address).
 Here, address of the value is passed in the function, so actual and formal
arguments share the same address space.
 Hence, value changed inside the function, is reflected inside as well as
outside the function.
Refer Example program callbyvalue.cpp
Refer Example program callbyref.cpp
Overloaded Function
 C++ allows you to specify more than one definition for a function name
or an operator in the same scope, which is called function
overloading and operator overloading respectively.

 Function Overloading:
 We can have multiple definitions for the same function name in the same scope.
 The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list.
 We cannot overload function declarations that differ only by return type.
Example: void print(int i)
void print(double f)
void print(char* c)

Refer Example program funoverload.cpp


Inline Functions
 C++ inline function is powerful concept that is commonly used
with classes. If a function is inline, the compiler places a copy of the
code of that function at each point where the function is called at
compile time.
 Any change to an inline function could require all clients of the
function to be recompiled because compiler would need to replace
all the code once again otherwise it will continue with old
functionality.
Syntax:
inline <return type > <function_name>(<param_list)
{
____
}
Refer Example program inline.cpp
Default arguments
A default argument is a value provided in function declaration
that is automatically assigned by the compiler if caller of the
function doesn’t provide a value for the argument with
default value.
Example:
int sum(int x, int y, int z=0, int w=0)
{
return (x + y + z + w);
}

Refer Example program defaultarg.cpp


Return by reference
 A C++ function can return a reference in a similar way as it returns
a pointer.
 When a function returns a reference, it returns an implicit pointer to
its return value. This way, a function can be used on the left side of
an assignment statement.

Syntax:
int vals[] = {10, 12, 33, 24, 50};
int& setValues( int i )
{
int vals[i]; // return a reference to the ith element
}
Refer Example program returnbyref.cpp

You might also like