Unit 4 Oops
Unit 4 Oops
Unit-4 OOPs
Unit-4
Syllabus
Overview of C language:
3. All program code of c can be executed in C++ but converse many not be
possible
For solving the problems, the problem is divided into a number of modules. Each
module is a subprogram.
The program written in C++ language follows this basic structure. The sequence of
sections should be as they are in the basic structure. A C program should have one
or more sections but the sequence of sections is to be followed.
1. Documentation section : comes first and is used to document the use of logic or
reasons in your program. The documentation is done in C language with /* and */
2. Linking section : 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.
e.g. #include using namespace std
3. Definition section: It is used to declare some constants and assign them some
value. e.g. #define MAX 25 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 & class declarations: the variables and class
definitions which are used throughout the program (including main and other
functions) are declared so as to make them global
5.Member function definition : The data components of a class are called data
members and function components of a class are called member functions
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.
section main() {
Declaration section
Executable section}
namespace: namespace is used to define a scope that could hold global identifiers.
A classes ,functions and templates are declared within the namespace named
namespace namespace_name {
ex:
#include<iostream>
display(200);
return 0;}
#include<iostream>
This directive causes the preprocessor to add content of iostream file to the
program.
some old versions of C++ used iostream.h .if complier does not support ANSI
(american nation standard institute) C++ then use header file iostream.h
IDENTIFIERS: Identifiers are the names given to various program elements such
as variables, functions and arrays. These are user defined names consisting of
sequence of letters and digits.
Identifiers may have any length but only first 31 characters are significant.
Space 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
Note: Some compilers of C recognize only the first 8 characters only; because of
this they are unable to distinguish identifiers with the words of length more than
eight characters.
It is an identifier used to store the value of particular data type in the memory.
Identifiers may have any length but only first 31 characters are significant.
Variable declaration: The declaration of variable gives the name for memory
location and its size and specifies the range of value that can be stored in that
location.
Syntax:
float x=2.3;
CONSTANTS:
Constants refer to values that do not change during the execution of a program.
1. Primary constants:
a)Numeric constants
Integer constants.
b)Character constants
String constants
2.Secondary constants:
Enumeration constants.
Symbolic constants.
1.Commas and blank spaces are not permitted within the constant.
3.The value of a constant must be within its minimum bounds of its specified data
type.
Floating point constants or Real constants : The numbers with fractional parts are
called real constants.
These are the numbers with base-10 which contains either a decimal part or
exponent (or both).
Exponent: It is an integer number with an optional plus (+) or minus (-) sign.
1.23456E+3 (1.23456×10 )3
Character constants:-
Example:
“MRCET” “12345”
Enumeration:
The enumerator names are usually identifiers that behave as constants in the
language. A variable that has been declared as having an enumerated type can be
assigned any of the enumerators as a value.
declaration of variable:
today=wednesday;
#include <iotream.h>
int main(){
today=wednesday;
return 0; }
Output 4 day
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operator
8. unary operator
9. Special operators
1.Decision making statements:- These statements are used to control the flow of
execution of a program
1.Simple if
2.if else
3.nested if else
continue: A continue statement is used in loops to repeat the loop for the next value
by transferring control back to the beginning of the loop and ignoring the
statements that come after it.
FUNCTION OVERLOADING
For example, an overloaded add() function handles different type of data as shown
below.
//declarations
// function calls
Typecasting:
Type casting refers to the conversion of one data type to another in a program.
Typecasting can be done in two ways: automatically by the compiler and manually
by the programmer or user. Type Casting is also known as Type Conversion.
For example, suppose the given data is an integer type, and we want to convert it
into float type.
int num = 5;
float x;
x = float(num);
x = 5.0
Type Casting is divided into two types: Implicit conversion or Implicit Type
Casting and Explicit Type Conversion or Explicit Type Casting.
It automatically converted from one data type to another without any external
intervention such as programmer or user. It means the compiler automatically
converts one data type to another.
All data type is automatically upgraded to the largest type without losing any
information.
It can only apply in a program if both variables are compatible with each other.
It is manually cast by the programmer or user to change from one data type to
another type in a program. It means a user can easily cast one data to another
according to the requirement in a program.
In this casting, we can upgrade or downgrade the data type of one variable to
another in a program.
Output:
C++ Functions
Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.
Floating point constants or Real constants : The numbers with fractional parts
are called real constants. Decimal notation: 1234.56, 75.098, 0.0002, -0.00674.
Character constants:-
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute
code. But you can also create your own functions to perform certain actions.
void myFunction(){
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use",
and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it
is called:
Example
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
Inline function
If make a function as inline, then the compiler replaces the function calling
location with the definition of the inline function at compile time.
Any changes made to an inline function will require the inline function to be
recompiled again because the compiler would need to replace all the code with a
new code; otherwise, it will execute the old functionality.
Inside the main() method, when the function fun1() is called, the control is
transferred to the definition of the called function. The addresses from where the
function is called and the definition of the function are different. This control
transfer takes a lot of time and increases the overhead.
When the inline function is encountered, then the definition of the function is
copied to it. In this case, there is no control transfer which saves a lot of time and
also decreases the overhead.
1. #include <iostream>
2. using namespace std;
3. inline int add(int a, int b) {
4. return(a+b); }
5. int main() {
6. cout<<"Addition of 'a' and 'b' is:"<<add(2,3);
7. return 0; }
Once the compilation is done, the code would be like as shown as below:
1. #include<iostream>
2. using namespace std;
3. inline int add(int a, int b) {
4. return(a+b); }
5. int main() {
6. cout<<"Addition of 'a' and 'b' is:"<<return(2+3);
7. return 0; }
o If a function is recursive.
o If a function contains a loop like for, while, do-while loop.
o If a function contains static variables.
o If a function contains a switch or go to statement
o The variables that are created inside the inline function will consume
additional registers.
o If we use many inline functions, then the binary executable file also becomes
large.
o The use of so many inline functions can reduce the instruction cache hit rate,
reducing the speed of instruction fetch from the cache memory to that of the
primary memory.
#include <iostream>
// Inline function
int main(){
cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;
cout << "Max (20, 0): " << Maximum(20, 0) << endl;
return 0;}
Output:
Max (100, 1000): 1000
Max (20, 0): 20
2. 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:
Example of Macro:
#include <iostream>
int main(){
return 0;}
Output:
Max (100, 1000):1000
Max (20, 0):20
Through inline function, the class’s Whereas macro can’t access the class’s
2. data members can be accessed. data members.
3. In the case of inline function, the Whereas in the case of macros, the
In C++, inline may be defined either Whereas the macro is all the time
5. inside the class or outside the class. defined at the beginning of the program.
Inline is not used in competitive While the macro is very much used in
8. programming. competitive programming.
Friend Class A friend function is a function which is not the member or the class
instead of that it can access private and protected members of the class.
A friend function in C++ is defined as a function that can access private,
protected and public members of a class. The friend function is declared using
the friend keyword inside the body of the class.
class className {
... .. ...
friend returnType functionName(arguments);
... .. ...
}
Example 1: Working of friend Function
// C++ program to demonstrate the working of friend function
#include <iostream>
using namespace std;
class Distance {
Output Distance: 5
A virtual function is a member function in the base class that we expect to redefine
in derived classes.
When you refer to derived class object using a pointer of a reference to base class,
you can call a virtual function for that object and can execute the derived class
functions.
class Base {
public:
void print() {
// code
}
};
// Statement 2
cout << sum(10, 15, 25) << endl;
// Statement 3
cout << sum(10, 15, 25, 30) << endl;
return 0;}
O/P: 25
50
80
2) If function overloading is done containing the default arguments, then we need
to make sure it is not ambiguous to the compiler, otherwise it will throw an error.
// CPP Program to demonstrate Function overloading in
// Default Arguments
#include <iostream>
using namespace std;
// A function with default arguments, it can be called with
// 2 arguments or 3 arguments or 4 arguments.
int sum(int x, int y, int z = 0, int w = 0)
{ return (x + y + z + w);}
int sum(int x, int y, float z = 0, float w = 0)
{ return (x + y + z + w);}
// Driver Code
int main()
{ cout << sum(10, 15) << endl;
cout << sum(10, 15, 25) << endl;
cout << sum(10, 15, 25, 30) << endl;
return 0; }
3) A constructor can contain default parameters as well. A default constructor can
either have no parameters or parameters with default arguments.
// CPP code to demonstrate use of default arguments in
// Constructors
#include <iostream>
using namespace std;
class A { private:
int var = 0;
public: A(int x = 0): var(x){}; // default constructor with one argument