Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
90 views103 pages

OOSD Unit-4

oops in cpp

Uploaded by

Anusha Maurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views103 pages

OOSD Unit-4

oops in cpp

Uploaded by

Anusha Maurya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

OBJECT ORIENTED SYSTEM DESIGN(OOSD)

BATCH 2023-2024
OVERVIEW OF C LANGUAGE:
1.C language is known as structure oriented language or procedure oriented language
2.Employs top-down programming approach where a problem is viewed as a sequence of tasks to
be performed.
3.All program code of c can be executed in C++ but converse many not be possible
4. Function overloading and operator overloading are not possible.
5. Local variables can be declared only at the beginning of the block.
6. Program controls are through jumps and calls to subroutines.
7.Polymorphism, encapsulation and inheritance are not possible.
For solving the problems, the problem is divided into a number of modules. Each module is a
subprogram.
8. Data abstraction property is not supported by procedure oriented language.
9. Data in procedure oriented language is open and can be accessed by any function.
OVERVIEW OF C++ LANGUAGE:

1. C++ can be considered as an incremental version of c language which consists all programming language constructs with newly added
features of object oriented programming.
2. C++ is object oriented programming language.
3. The file extension of C++ program is “.CPP”
4. Function overloading and operator overloading are possible.
5. Variables can be declared in inline i.e. when required
6. In c++ more emphasis is give on data rather than procedures.
7. Polymorphism, encapsulation and inheritance are possible.
8. Data abstraction property is supported by c++.
9. Data access is limited. It can be accessed by providing various visibility modes both for data and member functions.
10. Dynamic binding is supported by C++
11. It supports all features of c language
12. It can be called as an incremental version of c language
DIFFERENCE BETWEEN PROCEDURE ORIENTED PROGRAMMING
(POP) & OBJECT ORIENTED PROGRAMMING (OOP)
DIFFERENCE BETWEEN PROCEDURE ORIENTED PROGRAMMING
(POP) & OBJECT ORIENTED PROGRAMMING (OOP)
BASIC STRUCTURE OF C++ LANGUAGE:

A C++ program should have one or more sections but the sequence of sections is to be
followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section & class declarations
5. Member function definition
6. Main function
1. DOCUMENTATION SECTION :

1. Document section comes first and is used to document the use of logic or reasons in
your program.
2. It can be used to write the program's objective, developer and logic details.
3. The documentation is done in C++ language with /* and */ . Whatever is written
between these two are called comments.
2. LINKING SECTION :

1. This section tells the compiler to link the certain occurrences of keywords or functions in
your program to the header files specified in this section.
2. e.g. #include<iostream>
using namespace std;
3. Directive causes the preprocessor to add the contents of the iostream file to the program. It
contains declarations for cout and cin.
4. cout is a predefined object that represents the standard output stream. The operator << is an
insertion operator, causes the string in double quotes to be displayed on the screen.
5. The identifier cin is a predefined object in C++ that corresponds to the standard input stream.
The operator >> is known as extraction operator. It extracts the value from the keyboard and
assigns it to the value variable on its right.
3. DEFINITION SECTION :

1. It is used to declare some constants and assign them some value. e.g. #define MAX 25

2. Here #define is a compiler directive which tells the compiler whenever MAX is found
in the program replace it with 25.
4. GLOBAL DECLARATION SECTION :

1. Here the variables and class definations which are used through out the program
(including main and other functions) are declared so as to make them global(i.e
accessible to all parts of program).
2. A CLASS is a collection of data and functions that act or manipulate
the data. The data components of a class are called data members and function
components of a class are called member functions.
3. A class can also termed as a blue print or prototype that defines the variable or
functions common to all objects of certain kind.
4. It is a user defined data type.
5. e.g. int i; //this declaration is done outside and before main()
5. SUB PROGRAM OR FUNCTION SECTION :

This has all the sub programs or the functions which


our program needs.
void display()
{
cout<<”C++ is better that C”;
}
6. MAIN FUNCTION SECTION :

 It tells the compiler where to start the execution.


 main() {
point from execution starts
}

 main function has two sections


1. declaration section : In this the variables and their data types are declared.
2. Executable section or instruction section : This has the part of program which
actually performs the task we need.
NAMESPACE:

1. Namespace is used to define a scope that could hold global identifiers.


2. ex:-namespace scope for c++ standard library.
3. A classes, functions and templates are declared within the namespace named
std, using namespace std;
4. user defined name space:
syntax for defining name space is:
namespace namespace_name
{
//declarations of variables, functions, classes etc...
}
NAMESPACE:

1. ex:
#include<iostream>
using namespace std;
namespace sample
{
int m;
void display(int n)
{
cout<<"in namespace N="<<n<<endl;
}
}
IDENTIFIERS:

1. Identifiers are the names given to various program elements such as variables, functions and
arrays.
2. These are user defined names consisting of sequence of letters and digits.
3. Rules for declaring identifiers:
 The first character must be an alphabet or underscore.
 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.
 Upper and lower case letters are different.
IDENTIFIERS:

1. Examples of valid identifiers:


a, x, n, num, SUM, fact, grand_total, sum_of_digits, sum1
2. Examples of Invalid identifiers: $amount, ³num, grand-total, sum of digits, 4num.
$amount : Special character is not permitted
grand-total : hyphen is not permitted.
sum of digits : blank spaces between the words are not allowed.
4num : should not start with a number (first character must be a letter or underscore
VARIABLES:

1. A named memory location is called variable.


2. It is an identifier used to store the value of particular data type in the memory.
3. Since variable name is identifier we use following rules which are same as of identifier
4. Rules for declaring Variables names:
 The first character must be an alphabet or underscore.
 It must consist of only letters, digits and underscore.
 Identifiers may have any length but only first 31 characters are significant.
 It must not contain white space or blank space.
 We should not use keywords as identifiers.
 Upper and lower case letters are different.
 Variable names must be unique in the given scope
VARIABLE DECLARATION:

1. The declaration of variable gives the name for memory location and its size.
2. It specifies the range of value that can be stored in that location.
3. Syntax:
Data_type variable_name;
4. Ex:
int a=10;
float x=2.3;
CONSTANTS:

1. Constants refer to fixed values that the program may not alter and they are called literals.
2. Constants can be of any of the basic data types and can be divided into Integer Numerals,
Floating-Point Numerals, Characters, Strings and Boolean Values.
3. Again, constants are treated just like regular variables except that their values cannot be
modified after their definition.
4. Integer Literals: An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
 85 // decimal
 0213 // octal
 0x4b // hexadecimal
ENUM:

1. Enumerated type (enumeration) is a user-defined data type which can be assigned


some limited values.
2. These values are defined by the programmer at the time of declaring the enumerated
type.
3. For example: If a gender variable is created with value male or female. If any other
value is assigned other than male or female then it is not appropriate. In this situation,
one can declare the enumerated type in which only male and female values are
assigned.
4. Syntax:
enum enumerated-type-name{value1, value2, value3…..valueN};
ENUM:

1. // Defining enumYear
2. enum year { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec };
3. int main()
4. {
5. int i;
6. // Traversing the year enum
7. for (i = Jan; i <= Dec; i++)
8. cout << i << " ";
9. return 0;
10. }
11. Output:
12. 0 1 2 3 4 5 6 7 8 9 10 11
OPERATORS:

1. An operator is a symbol that tells the compiler to perform specific mathematical


or logical manipulations.
2. C++ is rich in built-in operators and provide the following types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
ARITHMETIC OPERATORS:
THE RELATIONAL OPERATORS:
THE LOGICAL OPERATORS:
THE BITWISE OPERATORS:
THE ASSIGNMENT OPERATORS:
MISC OPERATORS:
Sr. No Operator & Description

sizeof

1 sizeof operator returns the size of a variable. For example, sizeof(a), where ‘a’ is integer, and will return 4.

Condition ? X : Y

2 Conditional operator (?). If Condition is true then it returns value of X otherwise returns value of Y.

3 Comma operator causes a sequence of operations to be performed. The value of the entire comma expression is the value of the last expression of the comma-separated list.

. (dot) and -> (arrow)

4 Member operators are used to reference individual members of classes, structures, and unions.

Cast

5 Casting operators convert one data type to another. For example, int(2.2000) would return 2.

&

6 Pointer operator & returns the address of a variable. For example &a; will give actual address of the variable.

7 Pointer operator * is pointer to a variable. For example *var; will pointer to a variable var.
PRECEDENCE OF OPERATORS :
TYPECASTING:

1. A type cast is basically a conversion from one type to another.


2. There are two types of type conversion:
 Implicit Type Conversion
 Explicit Type Conversion
IMPLICIT TYPE CONVERSION:

1. Also known as ‘automatic type conversion’.


2. Done by the compiler on its own, without any external trigger from the user.
3. Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
4. All the data types of the variables are upgraded to the data type of the variable with
largest data type.
5. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long ->
float -> double -> long double
IMPLICIT TYPE CONVERSION:

1. // An example of implicit conversion


2. int main()
3. {
4. int x = 10; // integer x
5. char y = 'a'; // character c Output:
6. // y implicitly converted to int. ASCII x = 107
7. // value of 'a' is 97 y=a
8. x = x + y; z = 108
9. // x is implicitly converted to float
10. float z = x + 1.0;
11. cout << "x = " << x << endl << "y = " << y << endl << "z = " << z << endl;
12. return 0;
13. }
EXPLICIT TYPE CONVERSION:

1. This process is also called type casting and it is user-defined.


2. Here the user can typecast the result to make it of a particular data type.
3. In C++, it can be done by two ways:
 Converting by assignment: This is done by explicitly defining the required type in
front of the expression in parenthesis. This can be also considered as forceful casting.
 Syntax: (type) expression
 where type indicates the data type to which the final result is converted.
EXPLICIT TYPE CONVERSION:

1. // explicit type casting


2. int main()
3. {
4. double x = 1.2;
5. // Explicit conversion from double to int
6. int sum = (int)x + 1;
7. cout << "Sum = " << sum;
8. return 0;
9. }
10. Output:
11. Sum = 2
EXPLICIT TYPE CONVERSION:

1. Conversion using Cast operator: A Cast operator is an unary operator which forces one data type to be
converted into another data type.
2. int main()
3. {
4. float f = 3.5;
5. // using cast operator
6. int b = static_cast<int>(f);
7. cout << b;
8. }
9. Output:
10. 3
CONTROL STRUCTURES:

1. Control Structures are just a way to specify flow of control in programs.


2. Any algorithm or program can be more clear and understood if they use self-
contained modules called as logic or control structures.
3. It basically analyzes and chooses in which direction a program flows based on certain
parameters or conditions.
CONTROL STRUCTURES:

Control
Statement

Selection Statement Iteration Statement Jump Statement

If If-else switch break continue return

while do for
CONTROL STRUCTURES:
If(test expression) Nesting of If—else Statement
{ If(test condition1)

Statement-block; {

} if(test condition2)

{
----------------------------------------------------------------
Statement-1;
If-else statement
}
if(test expression)
else
{ {
True-Block Statement(s); Statement-2;

} }

Else }

else
{
{
False-Block statement(s);
Statement-3;
}
}
CONTROL STRUCTURES:
CONTROL STRUCTURES:
Switch(expression)

Case value-1:

block-1;

break;

Case value-2:

block-2;

break;

……

……

default:

default-block;

break;

}
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
FUNCTION IN C++
MACRO
It is also called preprocessors directive. The macros are defined by the #define keyword. Before the
program compilation, the preprocessor examines the program whenever the preprocessor detects the macros
then preprocessor replaces the macro by the macro definition.
Syntax of Macro:
#define MACRO_NAME Macro_definition
Example of Macro:

#include <iostream>
using namespace std;
// macro with parameter
#define MAXIMUM(a, b) (a > b) ? a : b
// Main function for the program Output:
int main()
{
Max (100, 1000):1000 Max (20, 0):20
cout << "Max (100, 1000):";
int k = MAXIMUM(100, 1000);
cout << k << endl;
cout << "Max (20, 0):";
int k1 = MAXIMUM(20, 0);
cout << k1;
return 0;
}
DIFFERENCE BETWEEN INLINE FUNCTION AND MACRO
S.NO Inline Macro

1. An inline function is defined by the inline keyword. Whereas the macros are defined by the #define keyword.

2. Through inline function, the class’s data members can be accessed. Whereas macro can’t access the class’s data members.

3. In the case of inline function, the program can be easily debugged. Whereas in the case of macros, the program can’t be easily debugged.

Whereas in the case of macro, the arguments are evaluated every time
4. In the case of inline, the arguments are evaluated only once.
whenever macro is used in the program.

In C++, inline may be defined either inside the class or outside the Whereas the macro is all the time defined at the beginning of the
5.
class. program.

In C++, inside the class, the short length functions are automatically
6. While the macro is specifically defined.
made the inline functions.

7. Inline is not as widely used as macros. While the macro is widely used.

8. Inline is not used in competitive programming. While the macro is very much used in competitive programming.

While the macro is not terminated by any symbol, it is terminated by a


9. Inline function is terminated by the curly brace at the end.
new line.
FRIEND FUNCTION
 A friend function of a class is defined outside that class' scope but it has the right to access all private and protected members
of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.
 A friend can be a function, function template, or member function, or a class or class template, in which case the entire class
and all of its members are friends.
 To declare a function as a friend of a class, precede the function prototype in the class definition with keyword friend.
 Characteristics of a Friend function:
• The function is not in the scope of the class to which it has been declared as a friend.
• It cannot be called using the object as it is not in the scope of that class.
• It can be invoked like a normal function without using the object.
• It cannot access the member names directly and has to use an object name and dot membership operator with the member
name.
• It can be declared either in the private or the public part.
FRIEND FUNCTION

#include <iostream> // Note: printWidth() is not a member function of any class.


using namespace std;
class Box { void printWidth( Box box ) {
double width; /* Because printWidth() is a friend of Box, it can
directly access any member of this class */
public: cout << "Width of box : " << box.width <<endl;
friend void printWidth( Box box ); }
void setWidth( double wid ); // Main function for the program
}; int main() {
// Member function definition Box box;
void Box::setWidth( double wid ) { // set box width without member function
width = wid; box.setWidth(10.0);
} // Use friend function to print the wdith.
printWidth( box );
return 0;
}
VIRTUAL FUNCTION
 A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a
derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can
call a virtual function for that object and execute the derived class’s version of the function.
• Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or
pointer) used for function call.
• They are mainly used to achieve Runtime polymorphism
• Functions are declared with a virtual keyword in base class.
• The resolving of function call is done at Run-time
VIRTUAL FUNCTION
#include <iostream>
using namespace std;
int main()
{
class base {
base* p;
public:
derived obj1;
void fun_1() { cout << "base-1\n"; }
p = &obj1;
virtual void fun_2() { cout << "base-2\n"; }
// Early binding because fun1() is non-virtual in base
virtual void fun_3() { cout << "base-3\n"; }
p->fun_1();
virtual void fun_4() { cout << "base-4\n"; }
// Late binding (RTP)
};
p->fun_2();
// Late binding (RTP)
class derived : public base {
p->fun_3();
public:
// Late binding (RTP)
void fun_1() { cout << "derived-1\n"; }
p->fun_4();
void fun_2() { cout << "derived-2\n"; }
p->fun_4(5);
void fun_4(int x) { cout << "derived-4\n"; }
}
};
VIRTUAL FUNCTION
Rules for Virtual Functions
1. Virtual functions cannot be static.
2. A virtual function can be a friend function of another class.
3. Virtual functions should be accessed using pointer or reference of base class type to achieve run time
polymorphism.
4. The prototype of virtual functions should be the same in the base as well as derived class.
5. They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived
class to override (or re-define the virtual function), in that case, the base class version of the function is used.
Function Declaration
• A function can be defined as:
Syntax : return_type function_name(arguments)
{
body of the function
}
For e.g :
int add(int a,int b)
{
return a+b;
}
Calling a Function
main()/function_1()
• A function can be called {
in a main() function or in body
function(passing values);
other functions. }
• When it is called inside For e.g :
itself than it called as main()
{
recursive function. int a,b;
cout<<“Sum=“<<add(a,b);
}

int add(int x,int y)


{
return x+y;
}
Return by reference
 Reference can also be return in a
function.
 Int& Func()
 {
 return a; // Return reference of that
function
 }
Inline Functions
• If a function is inline than:
– Compiler puts its code at the place
where it is called at compile time
inline return_type
– To define a function as inline function_name(args)
function {
//one line code
• use the keyword “inline” just
before the return type. }
– The compiler ignore the inline
qualifier in case defined function is
more than a line.
Inline Function (example)
#include <iostream>
using namespace std;
inline int Max(int x, int y) Output:
{ Max (20,10): 20
Max (0,200): 200
return (x > y)? x : y;
Max (100,1010): 1010
}
// Main function for the program
int main( )
{
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) <<
endl;
return 0;
}
Why Inline functions
• Objective of using functions:
– To save memory space, when a
Jumping to a function
function is likely to be called
many times. Saving the registers
Pushing arguments in to the
• When a function is small enough stack
(only one line of code) these Returning to the calling
things would be a wastage of
function
time and resources.
Macro in C++
• It is also called preprocessors directive. The macros
are defined by the #define keyword.
• Before the program compilation, the preprocessor
examines the program whenever the preprocessor
detects the macros then preprocessor replaces the
macro by the macro definition.
Macro example
Inline vs Macro

You might also like