Unit 1 - Fundamental of OOP - Final

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

Unit 1: Fundamental of OOP

Syllabus:-
Introduction to object-oriented programming, Need of object-oriented programming,
Fundamentals of object-oriented programming: Namespaces, objects, classes, data
members, methods, messages, data encapsulation, data abstraction and information hiding,
inheritance, polymorphism. Benefits of OOP, C++ as object oriented programming
language.

C++ Programming- C++ programming Basics, Data Types, Structures, Enumerations,


control structures, Arrays and Strings, Class, Object, class and data abstraction, Access
specifiers, separating interface from implementation.

Functions- Function, function prototype, accessing function and utility function,


Constructors and destructor, Types of constructor ,Objects and Memory requirements,
Static members: variable and functions, inline function, friend function.
Programmers write instructions in various programming languages to perform their computation
tasks such as:
1. Machine Level Language
2. Assembly Level Language
3. High Level Language

Machine level Language : (ASCII code 0100 0001 represent letter A’’)
Machine code or machine language is a set of instructions executed directly by a computer's central
processing unit (CPU). Each instruction performs a very specific task, such as a load, a jump, or an ALU
operation on a unit of data in a CPU register or memory. Every program directly executed by a CPU is
made up of a series of such instructions.

Assembly level Language :


An assembly language (or assembler language) is a for a computer, or other programmable device, in
which there is a very strong (generally one-to-one) correspondence between the language and the
architecture's machine code instructions. Assembly language is converted into executable machine
code by a utility program referred to as an assembler; the conversion process is referred to as
assembly, or assembling the code.
High level Language :
High-level language is any programming language that enables development of a program in
much simpler programming context and is generally independent of the computer's hardware
architecture. High-level language has a higher level of abstraction from the computer, and
focuses more on the programming logic rather than the underlying hardware components such
as memory addressing and register utilization.

.The first high-level programming languages were designed in the 1950s. Now there are dozens
of different languages, including Ada , BASIC, COBOL, C, C++, JAVA, FORTRAN, LISP, Pascal, and
Prolog

The high-level programming languages are broadly categorized in to two categories:

(iv) Procedure oriented programming(POP) language.


(v) Object oriented programming(OOP) language.
Procedure Oriented Programming
• In POP, the problem is viewed as a set of • A typical program structure of the POP
tasks. A set of functions are written to is as shown in below fig:
accomplish this tasks.

• In POP, primary focus is on functions.

• Most of the functions share global data.


Data moves openly aroundthe system
from function to function.is no
control
There on global data.
Problems with procedural languages?
1. Functions have unrestricted access to global data.
2. Unrelated functions and data, provide poor model of real world.

1. Unrestricted Access:-
 Program structure become more difficult.
 Program become difficult to modify.
 Changes made to global data item may need rewriting all functions that access that items.
2. Provide a poor model of the real world

Real-world objects have both attributes and behavior.

Attributes
for people, eye color and job title;
for cars, horsepower and number of doors

Behavior
something a real-world object does in response to some stimulus.
If you apply the brakes in a car, it will generally stop
Object Oriented Programming
• The basic reason for the innovation of OOP
is to remove the flaws/drawbacks of
Procedural approach.
• OOP treats data as a critical element
and does not allow it to flow freely around
the system.
• It ties data closely to the functions
that operate on it, and does not allow
access to the outside functions.
• Data of one object can not be accessed
• OOP divides a problem into the by the functions of other object.
number of objects, then build data However, functions of one object can
and function around these objects. The be accessed by the functions of other
data of an object can be accessed by only object.
those functions which are associated with
the same object.
POP Vs OOP
Procedure Oriented Programming Object Oriented Programming
Divided Into In POP, program is divided into small In OOP, program is divided into parts
parts called functions called objects.

Importance In POP, Importance is not given to In OOP, Importance is given to the


data but to functions as well as data rather than procedures or
sequence of actions to be done. functions because it works as a real
world.

Approach POP follows Top Down approach. OOP follows Bottom Up approach.
Access POP does not have any access specifier. OOP has access specifiers named
Specifiers Public, Private, Protected, etc.

Data In POP, Data can move freely from In OOP, Data of an object can be
function to function in the system. accessed only by those functions
which are associated with the same
object.
POP Vs OOP
Procedure Oriented Programming Object Oriented Programming
Expansion To add new data and function in POP is OOP provides an easy way to add new
very difficult. data and function.

Data Access In POP, Most function uses Global data In OOP, data can not move easily from
for sharing, that can be accessed freely function to function, it can be kept
from function to function in the public or private so we can control the
system. access of data.

Data Hiding POP does not have any proper way for OOP provides Data Hiding using
hiding data so it is less secure. private access specifier, so provides
more security.

Examples C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET


Fundamentals of
Object-Oriented Programming
Features of object oriented programming …
• Emphasis(Importance) is given to data rather than Functions/Procedures

• Problem is divided into set of Objects rather than Functions/Procedures

• Data and functions of the object are tied together in data Structure
called Class/Object.

• Data of an object can not be accessed by the external functions.

• Objects may communicate through functions.

• It follows Bottom-Up approach.


Fundamentals of object-oriented programming
• Object
• Class
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message passing
Object:
• Objects are basic run-time entities in OOP.
• An Object can be physical as well as logical.
• An Object is an entity that has state, behavior and
identity.

• Example: Computer mouse is an object.


• Its state would be , Its color, size, brand etc.
• Its behavior would be left_click, right_click.
Physical objects…
• Object:

Pen Board Laptop

Bench Student Projector


Logical objects…
• Object:

Result Account

Bank Account
• Object (Attributes and
Operations):
OBJECT: CAR

Attributes (Properties)
Manufacturer Operations (Actions)
Model Start
Color Drive
Year Park
Price
• Object (Attributes and
Operations):

Attributes: Attributes Attributes:


Name : AccountNo
Age Company HolderName
Weigh Model Balance
t Weight
Operations: Operations: Operations:
Eat Drive Deposit
Sleep Stop Withdraw
Walk FillFuel Transfer
• Class:
• A class is an entity that helps the programmer to define new user defined data
type that behave like built-in datatype.

• Variable of class data type is known as object.

• Once a class is defined, we can create number of objects belonging to that


class.

• Example: if Fruit has been defined as a class, then statement :


Fruit mango;

• Will create an object mango, belonging to the class Fruit.


• Class:

Class: Blueprint (template) for object.


Object: Instance of class.
• Class:
Principles of OOP
• Abstraction:
▪ Abstraction refers to the act of representing essential features without
including the background details or explanations.

▪ Abstraction is the process of hiding the working style of an object, and


showing the information of an object in understandable manner.
Principles of OOP
• Abstraction:
Abstract View
Detailed View
Principles of OOP
• Encapsulation:

▪ The wrapping up of data and functions into a single unit


is known as encapsulation.

▪ In OOP, Encapsulation is achieved by binding data members


and functions into class.
▪ The insulation of the data from direct access by the program
is called data hiding or information hiding.
Principles of OOP
• Encapsulation:
Principles of OOP
▪ Inheritance:
• Inheritance is the process by which objects of one class acquire
the properties of objects of another class.

Vehicle

Land Water Air

Bus Car Ship Boat Aero plane Helicopter


• Here Vehicle class can have properties like Chassis no. , Engine, Colour etc.
• All these properties inherited by sub classes of vehicle class.
Principles of OOP
• Polymorphism:
▪ Polymorphism means ability to take more than one form.

▪ For example the operation addition.


▪ For two numbers the operation will generate a sum.

▪ If the operands are strings, then the operation would produce a third
string by concatenation.
Poly Morphism Polymorphism
(Many) (Forms) (Many Forms)
Principles of OOP
• Polymorphism:
Principles of OOP
• Message Passing:
“The process of invoking an operation on an object. In response to a
message the corresponding method is executed in the object”.
StudentObject FacultyObject

MgmtObject
Performance
Result
Principles of OOP
• Data Members:
Data members include members that are declared with any of the fundamental types,
as well as other types, including pointer, reference, array types, bit fields, and user-
defined types.
Principles of OOP
• Methods:
 Methods are functions that belongs to the class.
 There are two ways to define functions that belongs to a class:
1. Inside class definition. 2. Outside class definition.
class Example
class Example {
{ int a,b;
public: public:
void add() //method defined inside class void add(); //method declared inside class
{ };
------ void Example::add() //method defined outside class
------ {
} ------
}; }
int main() int main()
{ Example obj; { Example obj;
obj.add(); obj.add();
return 0; return 0;
} }
Principles of OOP
• Namespaces:
 A namespace is a declarative region that provides a scope to the identifiers (the
names of types, functions, variables, etc) inside it.

 Namespaces are used to organize code into logical groups and to prevent name
collisions that can occur especially when your code base includes multiple libraries.

e.g. using namespace std;

Here,
std is the namespace where ANSI C++ standard class libraries are defined.
Benefits & Applications of
OOP
Benefits of OOP
 Reusability
We can use single code many time in our entire application. This is done with
the use of a class.

 Data Redundancy

Data redundancy is a condition created within a database or data storage


technology in which the same piece of data is held in two separate places.

This can mean two different fields within a single database or two different
spots in multiple software environments or platforms. Whenever data is
repeated, it basically constitutes data redundancy
Benefits of OOP
 Code Maintenance
This feature is more of a necessity for any programming language, it helps users
from doing re-work in many ways. It is always easy and time-saving to maintain
and modify the existing codes by incorporating new changes into them.

 Security
With the use of data hiding and abstraction mechanism, we are filtering out
limited data to exposure which means we are maintaining security and
providing necessary data to view.

 Design Benefits
Object-Oriented Programs force the designers to have a long and extensive
design phase, which results in better designs and fewer flaws.
Benefits of OOP
 Better Productivity
This leads to more work done, finish a better program, having more inbuilt
features, and easier to read, write and maintain.

 Encapsulation
Encapsulation is used to hide the values or state of a structured data object
inside a class, preventing unauthorized parties’ direct access to them.

 Polymorphism
Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object
Applications of
OOP
 User interface design such as windows, menu.
 Real-Time Systems
 Simulation and Modeling.
 Object-oriented databases
 AI and Expert System
 Neural Networks and parallel programming
 Decision support and office automation systems etc.
Syllabus:-

C++ Programming- C++ programming Basics, Data Types, Structures, Enumerations,


control structures, Arrays and Strings, Class, Object, class and data abstraction, Access
specifiers, separating interface from implementation.
C++ as OOP language
 C++ is called object oriented programming (OOP) language because C++
language views a problem in terms of objects involved rather than the
procedure for doing it.
 Object oriented programming is always good for writing large business logics
and large applications or games.
 Developed by Bjarne Stroustrup.
 At AT&T Bell Laboratories in Murray Hill, New Jersey, USA.
 In the early 1979’s.
 C++ is a superset of C.
C++ is Partially OOPL
 Main function is outside the class :
 You can write a valid, well-coded, excellently-styled C++ program without using an object
even once.
 In C++, main function is mandatory, which executes first but it resides outside the
class and from there we create objects. So, here creation of class becomes optional and
we can write code without using class.
#include <iostream> class hello
using namespace std; {
public static void main(String args[])
int main() {
{ System.out.println("Hello World");
cout << "Hello World"; }
return 0; }
}
While in JAVA, main function is executed first and it reside in
the class which is mandatory
C++ is Partially OOPL
 Concept of Global variable :
 In C++, we can declare a variable globally, which can be accessible from anywhere.
 Anyone can access and modify those data, so it ensures encapsulations partially
#include <iostream>
using namespace std;
// Global variable declaration:
In JAVA, we can declare variable inside class only
int g = 50; and we can provide access specifiers to it

int main ()
{
// global variable g
cout << g;
// Local variable g
g = 20;
cout << g;

return 0;
}
C++ is Partially OOPL
 Availability of Friend function:

 Friend Class A friend class can access private and protected members of other class
in which it is declared as friend.
 It is sometimes useful to allow a particular class to access private members of other class.
Therefore, again the Object oriented features can be violated by C++.
C++ Program Structure
#include<iostream>
using namespace std;
class Example
{
//Class declaration, if any along with its member variables and functions
};
//global variables, if any
int main() //This is where the execution of program begins
{
//code
return 0;
}
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World";
return 0; Hello World
}
Basic Input / Output
Standard Output (cout)
• The cout object in C++ is an object of class ostream. It is used to display the output to
the standard output device i.e. monitor.
1.cout << "Output sentence"; // prints Output sentence on screen
2.cout << 120; // prints number 120 on screen
3.cout << x; // prints the content of x on screen

• << : Insertion operator (put to Operator)


1.cout << "Hello, " << "I am " << "a C++ statement";
To add a new-line, you may also use the endl manipulator.
2. cout << "First sentence." << endl;
3. cout << "Second sentence." << endl;
Basic Input / Output
Standard Input (cin)
• The cin object in C++ is an object of class istream. It is used to accept the input
from the standard input device i.e. keyboard.
>> : Extraction Operator (get from operator)
• Example:
1. int age;
2. cin >> age;
• cin can only process the input from the keyboard once the RETURN key has been
pressed.
1. cin >> a >> b;
COMMENTS IN C++

• C++ comments start with /* and end with */.

/* This is a comment */

/* C++ supports single-line and multi-line comments. All characters available inside any
comment are ignored by C++ compiler. */

• cout << "Hello World"; // prints Hello World


C++ Data Types
C++ Data Types
Built-In Data Types
C++ Data Types
User Defined Data Types- Structures
 User defined data type which allows you to combine data items of different kinds.
Example:
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book
C++ Data Types
User Defined Data Types- Union
 Union - user-defined type that uses same block of memory for each of its list
member
e.g.
union student
{
int roll_no;
int phone_number;
float percentage;
};
C++ Data Types
User Defined Data Types- Class
Class - defines a new data type, with more than one member variables and
member functions.
e.g.
class Books
{
char title[50];
char author[50];
public:
void get_book();
void show_book();
};
C++ Data
Types
User Defined Data Types- Enum

#include <iostream>
 Enumerations are used to define symbolic using namespace std;
constants(called an enumerator) enum direction {East, West, North, South};
 Each enumerator is a constant whose type is the int main()
{
enumeration. direction dir = North;
 To define an enumeration, keyword enum is used. cout<<dir<<endl;
cout<<East;
enum enum-name { list of names } var-list; return 0;
e.g. enum direction {East, West, North, South};
}
Output: 2
0
C++ Data Types
User Defined Data Types- typedef

 Using the keyword “typedef”, you can define new data


type names to the existing ones. #include <iostream>
using namespace std;
int main()
 Its syntax is: {
typedef <type> <newname>; typedef int num;
num a = 10, b = 15;
typedef float balance; num c = a + b + a - b;
cout << c;
 The use of a typedef can make the code easy to read and return 0;
}
also easy to port to a new machine.
Variables
 Variables to store various information.

 Variables are nothing but reserved memory


locations to store values.

 Examples:
 int a;
 float mynumber;
 int a, b, c;

Scope of variables
Control structures
 C++ has only three kinds of control structures, which we refer to as control statements:

Sequence statement
“sequence is a series of statements that executes one after another”

Conditional structure
 If Statement
 If-else
 Nested if-else
 Else if ladder
 Switch statement

Iteration structures (loops)


Loops cause a section of your program to be repeated a certain number of times.
 While
 do while
 for
Control structures
Control structures
The if Statement
 The if statement is the simplest of the decision statements

Question If the variable count exceeds 100, a single


statement that prints “Too many” is
A if (count<100) cout<< “Too many”;
B if (count>100) cout >> “Too many”;
C if (count>100) cout << “Too many”;
D None of these.
Control structures
The if...else Statement

if( x > 100 )


cout << “That number is greater than 100\n”;
else
cout << “That number is not greater than 100\n”;
Control structures
Nested if...else

if(a==b)
{
if(b==c)
cout << “a, b, and c are the same”;
}
else
cout << “a and b are different”;
Control structures
else...if Ladder

if( dir==’n’) //go north


y++;
else if( dir==’s’ ) //go south
y--;
else if( dir==’e’ ) //go east
x++;
else if( dir==’w’ ) //go west
x--;
else
x=0;
Control structures
Switch statement
The expression used in switch must be integral type ( int, char and enum). Any other type of
expression is not allowed
What should be the output of below program?
int main()
{
int a = 1;
switch(a)
{
case 1: cout<<"One";
case 2: cout<<"Two";
case 3: cout<<"Three";
default: cout<<"Default";
}
return 0;
}

Hint :- break; ???


The Conditional Operator
 The conditional operator is kind of similar to the if-else statement as it does follow the
same algorithm as of if-else statement but the conditional operator takes less space and
helps to write the if-else statements in the shortest way possible.

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators
Iteration structures (loops)
for Loop

 The for loop executes a section of code a fixed number of times.


 Used when you know, before entering the loop, how many times you want to execute the
code.
Iteration structures (loops)
for Loop
#include <iostream>
using namespace std;
#include <iostream> int main()
using namespace std; { 10
int main() int i;
{ for (i = 1; i < 10; i++);
int i; {
for (i = 1; i < 10; i++) cout << i << " ";
{ }
cout << i << " ";
} }

} Repeat nine times for (i=0; i<10; i++)


... do nothing (semicolon)
Open a new scope for local variables
123456789 {
... Cout << i ;
Close the scope }
As you can see, the operation that gets repeated is ; , not the cout.
Iteration structures (loops)
while Loop

 This loop generally used if you don’t know how many times you want to do something
before you start the loop?
#include <iostream>
using namespace std;
int main()
{
int i = 2 ;
i =i-1;
while(i)
{
cout<<"its a while loop";
i++ ;
}
return 0;
}
Iteration structures (loops)
do-while Loop
 This loop places the test expression at the end of the loop.
 When we want to guarantee that the loop body is executed at least once, even if test condition is
false.
break and countinue statement
 The break statement
The break statement takes you out of the bottom of a loop.
 The continue statement
Go back to the top of the loop when something unexpected happens .
Arrays and Strings
 An array as a collection of variables of the same type.
 In an array collection of items stored at contiguous memory locations
 Elements of an array can be accessed randomly using indices of an array.

Syntax:
type arrayName [ arraySize ];
Example:
22 47 12 21 33 60 Arrays Elements
0 1 2 3 4 5 Arrays Indices

Array Length : 6
First Index: 0
Last Index: 5
Arrays and Strings
 Initializing Arrays

Accept array elements from user and display it

int main()
{
int a[5];
int i;
for(i=0;i<5;i++)
{
cout<<“\n Enter Element:”;
cin>>a[i];
}
for(i=0;i<5;i++)
cout<<“\n”<<a[i];
return 0;
}
2D - Arrays
double sales[DISTRICTS][MONTHS];
Accept array elements from user and display it.
int main()
{
int a[3][4];
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
cout<<“\nEnter Element:”;
cin>>a[i][j];
}
}

for(i=0;i<3;i++)
for(j=0;j<3;j++)
cout<<“\n”<<a[i][j];
return 0;
}
C++ Strings
C++ provides following two types of string representations:
1. The C-style character string.
2. Strings that are objects of the string class.
 The C-style character string originated within the C language and continues to be
supported within C++.
 This string is actually a one-dimensional array of characters which is terminated by
a null character '\0'.
Example:
char greeting[] = "Hello";
C String-Manipulation Functions
In order to manipulate null terminated strings header file <cstring> is included in the program. This header
file provides the same functionality as string.h in C.

Function prototype Function description


char *strcpy Copies the string src into the character array dest. The
( char *dest, const char *src); value of dest is
returned.
char *strncpy Copies at most n characters of the string s2 into the
( char *s1, const char *s2, size_t n ); character array s1. The value of s1 is returned.
char *strcat Appends the string s2 to s1. The first character of s2
( char *s1, const char *s2 ); overwrites the
terminating null character of s1. The value of s1 is
returned.
char *strncat Appends at most n characters of string s2 to string s1.
( char *s1, const char *s2, size_t n ); The first character of s2 overwrites the terminating null
character of s1. The value of s1 is returned.
C String-Manipulation Functions
Function prototype Function description
int strcmp Compares the string s1 with the string s2. The
( const char *s1, const char *s2 ); function returns a value of zero, less than zero or
greater than zero if s1 is equal to, less than or greater
than s2, respectively.
size_t strlen Determines the length of string s. The number of
( const char *s ); characters preceding
the terminating null character is returned.
char *strrev Change all characters in a string to reverse order,
(char *s); excepting the terminating null character.
char * strstr Returns a pointer to the first occurrence of s2 in s1, or
( const char *s1, const char *s2 ); a null pointer if s2 is not part of s1.
C String-Manipulation Functions
//computes string’s length
Output
char a[20]="Program";
cout<< “Length of string a ”<<strlen(a) ; Length of string a = 7

// copying str1 to str2


char str1[20] = "C programming"; Output
char str2[20]; C programming
strcpy(str2, str1);
cout<<str2;

// concatenates str1 and str2 Output


char str1[100] = "This is ", str2[] = “C program"; This is C program
// the resultant string is stored in str1. C program
strcat(str1, str2);
cout<<str1;
cout<<str2;
C String-Manipulation Functions
//Compares two strings
char str1[] = "abcd", str2[] = "abCd", str3[] =
"abcd"; Output
int result; strcmp(str1, str2) = 32
strcmp(str1, str3) = 0
strcmp(str2, str1) = -32
// comparing strings str1 and str2
result = strcmp(str1, str2);
cout<<"strcmp(str1, str2) = “<<result;

// comparing strings str1 and str3


result = strcmp(str1, str3);
cout<<"strcmp(str1, str3) = “<<result;

// comparing strings str2 and str1


result = strcmp(str2, str1);
cout<<"strcmp(str2, str1) = “<<result;
C++ string Class
String operations

copy : Copy sequence of characters from string


compare : Compare strings
substr : Generate substring
find : Find content in string
rfind : Find last occurrence of content in string
find_first_of : Find character in string
find_last_of : Find character in string from the end
find_first_not_of: Find absence of character in string
find_last_not_of: Find non-matching character in string from the end
C++ string Class
Assign =
string s1;
string s2;
s1 = s2; // the contents of s2 is copied to s1
Append +=
string s1( "abc" );
string s2( "def" );
s1 += s2; // s1 = "abcdef" now
Indexing []
string s( "def" );
char c = s[2]; // c = 'f' now
s[0] = s[1]; // s = "eef" now
Concatenate +
string s1( "abc" );
string s2( "def" );
string s3;
s3 = s1 + s2; // s3 = "abcdef" now
C++ string Class
Assign =
string s1;
string s2;
s1 = s2; // the contents of s2 is copied to s1
Append +=
string s1( "abc" );
string s2( "def" );
s1 += s2; // s1 = "abcdef" now
Indexing []
string s( "def" );
char c = s[2]; // c = 'f' now
s[0] = s[1]; // s = "eef" now
Concatenate +
string s1( "abc" );
string s2( "def" );
string s3;
s3 = s1 + s2; // s3 = "abcdef" now
Access Specifiers
Access Specifiers

 Visibility of Data members & Member functions public –


accessed by member functions and all other non-member
functions in the program.
 private - accessed by only member functions of the class.
 protected - similar to private, but accessed by all the
member functions of immediate derived class
 default - all items defined in the class are private.
Object
Declare objects of a class with exactly the same sort of declaration that we declare
variables of basic types.

Example
Class and Data Abstraction

Abstraction means displaying only essential


information and hiding the details.
Class and Data Abstraction

void display() {
#include <iostream>
cout<<"a = " <<a << endl;
using namespace std;
cout<<"b = " << b << endl;
}
class implementAbstraction
};
{
private:
int main() {
int a, b;
implementAbstraction obj;
obj.set (10, 20);
public:
obj.display ();
return 0;
// method to set values of
}
// private members
void set(int x, int y)
OUTPUT:
{
a= 10
a = x;
b= 20
b = y;
}
We are not allowed to access the variables a and b directly, however one can call the function set() to set
the values in a and b and the function display() to display the values of a and b.
Separating Interface from Implementation

 Class declaration is the abstract definition


of interface.
 The functions include the details of the
implementation.

It is possible to separate interface from the


implementation by placing them in separate
files.

The class declaration goes in a header file


with a .h extension whereas implementation
goes in the .cpp file which must include the
user defined header file.
Separating Interface from Implementation

//Cal.cpp
// implementation of functions

//cal.h header file #include "cal.h"


int Cal::add(int x,int y,int z)
class Cal {
{ a=x;
int a,b,c; b=y;
public: c=z;
int add(int x,int y,int z); return a+b+c;
int sub(int x,int y); }
}; int Cal::sub(int p,int q)
{
a=p;
b=q;
return a-b;
}
Syllabus:-

Functions- Function, function prototype, accessing function and utility function,


Constructors and destructor, Types of constructor ,Objects and Memory requirements,
Static members: variable and functions, inline function, friend function.
Function in C++
 A function is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a function.

 Functions are used to perform certain actions, and they are important for reusing
code: Define the code once, and use it many times.

 The function’s code is stored in only one place in memory, Even though the function is
executed many times in the course of the program.

 Three steps..
A. Function declaration/ function prototype
B. Function definition
C. Function call
Functions in C++

 Experience has shown that the best way to develop and maintain
large programs is to construct it from smaller pieces(Modules)
 This technique is Called “Divide and Conquer”.
Bad Development Approach Wise Development Approach

main()
main()
{
{
}
-----
-----
. function f1()
{
.
---
----
}
-----
Return 0; function f2()
} {
---
}
Function Declaration/ Function Prototype

Function prototype serves the following purposes:

1) It states the return type of the data that the function will return.
2) It states the number of arguments passed to the function.
3) It states the data types of the each of the passed arguments.
4) It states the order in which the arguments are passed to the function.

Syntax

Example for declaration of function


• int square(int);

return-type function-name(argument list);


Function Definition

• Syntax format for function definition


returned-value-type function-name (parameter-list)
{
Declarations of local variables and Statements
}

– Parameter list
• Comma separated list of arguments
• Data type needed for each argument
• If no arguments, use void or leave blank
– Return-value-type
• Data type of result returned (use void if nothing returned)
Function Definition

 Example function
int square( int y )
{
return y * y;
}
 return keyword
– Returns data, and control goes to function’s caller
 If no data to return, use return;
– Function ends when reaches right brace
 Control goes to caller
 Functions cannot be defined inside other functions
Function Calling

 Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result

Function Name argument Output


3
cout<< sqrt(9);

Parentheses used to enclose argument(s)


// Creating and using a programmer-defined function.
#include <iostream.h>
Function prototype: specifies
int square( int ); // function prototype data types of arguments and
return values. square
int main()
expects an int, and returns
{
an int.
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function
call
Parentheses () cause function to be

Function Example
cout << endl; called. When done, it returns the result.
return 0; // indicates successful termination

} // end main

// square function definition returns square of an integer


int square( int y ) // y is a copy of argument to function
{
return y * y; // returns square of y as an
Definition of square. y is a
int copy of the argument passed.
Returns y * y, or y
} // end function square squared.

1 4 9 16 25 36 49 64 81 100
Parameter Passing Technique

 Actual Parameters:
The values/variables passed while calling a function are called actual parameters.

 Formal Parameters:
These are the variables written/declared in function definition/
prototype, and receive their values when a call to that function is made.

The value(s) of the actual parameters are copied to formal parameters when the call to
that function is made.
Parameter Passing Technique

Example:

int sum (int a, int b) //Format Parameters //Statement 1


{
return a+b;
}

int main()
{
int x=10,y=20;
int s = sum(x,y); //Actual Parameters //Statement 2

return 0;
}

In Statement 1, the variables a and b are called FORMAL PARAMETERS. In Statement 2 the arguments x and y are
called ACTUAL PARAMETERS (as they are the actual ones to hold the values, you can think it like this).
Parameter Passing Technique

//C++ program to illustrate call by value


#include <iostream>
using namespace std;

void func(int a, int b)


{
a += b;
cout <<"In func, a = " << a << " b = "<< b << endl;
}

int main(void)
{
int x = 5, y = 7;

// Passing parameters
func(x, y);
cout << "In main, x = " << x << " y = " << y;
return 0;
}
Parameter Passing Technique

1.While Passing Parameters using call by value , xerox copy of original parameter is created and passed to the called
function.

2.Any update made inside method will not affect the original value of variable in calling function.

//C++ program to illustrate call by value int main(void)


#include <iostream> {
using namespace std; int x = 5, y = 7;

void func(int a, int b) // Passing parameters


{ func(x, y);
a += b; cout << "In main, x = " << x << " y = " << y;
cout <<"In func, a = " << a << " b = "<< b << endl; return 0;
} }
Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
Parameter Passing Technique

1. While passing parameter using call by address scheme , we are passing the actual address of the
variable to the called function.

2. Any updates made inside the called function will modify the original copy since we are directly modifying
the content of the exact memory location.

#include<stdio.h> int main() {

void interchange(int *num1,int *num2) int num1=50,num2=70;


{ interchange(&num1,&num2);
int temp;
temp = *num1; printf("\nNumber 1 : %d",num1);
*num1 = *num2; printf("\nNumber 2 : %d",num2);
*num2 = temp;
} return(0);
}
Output:
Number 1 : 70
Number 2 : 50
<utility> in C++

It is a header file that contains utilities in unrelated domains.


 Pairs: These are the objects which can hold two different types of values.
 Generic Relational Approach: It is used for the relational operators !=, >, = under a specific
namespace: rel_ops.
 Generic swap function: This a standard definition used by default by the components of the
standard library for all types that do not provide their own overload: 1. swap.
// CPP program to use of swap function
// After swapping, a: 10 20 30 40 & b: _ _ _
#include <iostream>
_
#include <utility>
swap(a, b);
using namespace std; Output:
cout << "a contains:"; a contains:10
for (int i=0; i<4;i++) 20
int main ()
cout << a[i]<<endl; 30
{// a: _ _ _ _ (empty array in beginning)
40
int a[4];
return 0;
// Initializing, a: _ _ _ _ & b: 10 20 30 40
}
int b[] = {10, 20, 30, 40};
<utility> in C++

2. make_pair: It constructs a pair with its first element set to x and its second element set to y.
E.g.
// Initializing the pair with int type
pair <int, int> a;
pair <int, int> b;
a = make_pair (10, 20);
b = make_pair (15.5, 'B'); // conversion takes place from pair<double, char>

o/p  a: 10, 20
b: 15, 66

3. move: It moves as rvalue. move is used to indicate that an object may be “moved from”, i.e. allowing the
transfer of resources from an object(to be moved) to another object.
e.g.
string s = "Hello!!"; o/p  Hello Hi
string s1 = “Hi";
vector<string> str;
str.push_back (s); // It copies 's' in str
str.push_back (move(s1)); // It moves 's1' in the str(containing 's')
<utility> in C++

4. move (range of elements): It moves the elements in the range [first, last) into the range
beginning at result.

e.g.
string1 = {"Hi", “Hello", “How", "are", “you"};
string2 (5);

// use of move i.e.it moves from first to last element in string 1 to the string2 from it's(string 2)
starting
move ( string1.begin(), string1.begin()+5, string2.begin() );
Inline Functions

 An inline function is one in which the function code replaces the


function call directly.

 Inline class member functions


– if they are defined as part of the class definition, implicit
– if they are defined outside of the class definition, explicit, I.e.using
the keyword, inline.

 Inline functions should be short (preferable one-liners).


Inline Function in C++
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 of the class in which they are declared.

 To make a function as a friend of a class, it is declared inside the class either in private or in
public section with keyword friend before its declaration.

 Declaration:

class class_name
{
// syntax of friend function.
friend data_type function_name(argument/s);
};
Friend Function
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function declaration
};
int printLength(Box b) //friend function defination
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<endl;
return 0;
} O/P 10
Static Members
Static data members

 Static data members are class members that are declared using static keywords

 Only one copy of that member is created for the entire class and is shared by all the objects
of that class, no matter how many objects are created

 It is initialized before any object of this class is being created, even before main starts.
Static Function Members

 A static member function can be called even if no objects of the class exist
 the static functions are accessed using only the class name and the scope resolution
operator ::
 A static member function can only access
 static data member
 other static member functions
 any other functions from outside the class.
Friend Function

 We can also make a class a friend of another class.

 In that case, all the member function of the class declared as friend become
the friend functions of the other class.

Example:
class A
{ Class B is declared as a friend of class A in
friend class B;
the above code.
}; So, now all the member functions of class
class B B became friend functions of class A.
{

};
Function Overloading

 Two or more functions can have the same name but different
parameters
 Example:

int max(int a, int b) { float max(float a, float b) {


if (a>= b) if (a>= b)
return a; return a;
else else
retur retur
n b; n b;
} }
constructor
 A constructor is a special member function whose task is to initialize the
objects of its class.
 It is special because its name is same as the class name.
 The constructor is invoked whenever an object of its associated class is
created.
 Automatic initialization is carried out using a special member function
called a constructor. Example:
Syntax: class student
class class_name { int st_id;
{ public:
public: student()
class_name(); {
}; st_id=0;
}
constructor
Example

class add • When a class contains a


{ constructor, it is guaranteed that
int m, n ; an object created by the class will
public :
be initialized automatically.
add
(void) ; • add a ;
• Not only creates the object a of
}; type add but also initializes its
add :: add data members m and n to zero.
(void)
{
m = 0; n
Characteristics of Constructors

 They should be declared in the public section.

 They are invoked automatically when the objects are created.

 They do not have return types, not even void and they cannot return values.

 They cannot be inherited, though a derived class can call the base class
constructor.

 Like other C++ functions, Constructors can have default arguments.

 Constructors can not be virtual.


Types of Constructors

 Default Constructor
 Parameterized constructors
 Overloaded constructors
 Constructors with default argument
 Copy constructors
 Dynamic constructors
Default constructor

#include <iostream>  A constructor that accepts no parameters is


using namespace std;
class MyClass
called the default constructor.
{  The default constructor for class A is
int a, b;
public: A::A()
MyClass() // Default Constructor
{
a = 0;
b = 0; int main()
} {
void display() MyClass obj; 0
{ obj.display();
cout << "a: " << a; }
cout << "b: " << b; 0
}
};
Parameterized Constructors

 The constructors that can take arguments are called parameterized


constructors.
class add • When a constructor is parameterized, we must
{ pass the initial values as arguments to the
int m, n ; public : constructor function when an object is declared.
add (int, int) ;
------ • Two ways Calling:
}; o Explicit
add : : add (int x, • add sum = add(2,3);
int y) o Implicit
{ • add sum(2,3)
m = x; n = y; • Shorthand method
}
Copy Constructor

 A copy constructor is used to declare and initialize an object from another


object.
integer (integer & i) ;
integer I 2 ( I 1 ) ; or integer I 2 = I 1 ;
 The process of initializing through a copy constructor is known as copy
initialization.
 A reference variable has been used as an argument to the copy constructor.
Dynamic Constructors

 Allocation of memory to objects at the time of their construction is known


as dynamic construction of objects.

 The memory is created with the help of the new operator.

 The constructors can also be used to allocate memory while creating


objects.

 This will enable the system to allocate the right amount of memory for
each object when the objects are not of the same size.
Multiple Constructors in a Class
 C++ permits to use more than one constructors in a single class.
 Add( ) ; //No arguments
 Add (int, int) ; // Two arguments

class add • The first constructor receives no


{ arguments.
int m, n ; public :
add ( ) • The second constructor receives
{m = 0 ; n = 0;}
two integer arguments.
add (int a, int b)
{m = a ; n = b ;}
add (add & i) • The third constructor receives one
{m = i.m ; n = i.n;} add object as an argument.
};
Multiple Constructors in a Class

class add  Add a1; //default constructor


{
 Would automatically invoke the first constructor and set
int m, n ;
both m and n of a1 to zero.
public :
 Add a2(10,20); //parameterized constructor
add ( )
 Would call the second constructor which will initialize the
{m = 0 ; n = 0 ;}
data members m and n of a2 to 10 and 20 respectively.
add (int a, int b)
 Add a3(a2);
{m = a ; n = b ;}
add (add & i)
 Would invoke the third constructor which copies the values
of a2 into a3.
{m = i.m ; n = i.n ;}
};
 This type of constructor is called the “copy constructor”.

Constructor Overloading - More than one constructor function is defined in a class.


Constructors with Default Arguments
• It is possible to define constructors with default arguments.
• Consider
complex (float real, float imag = 0);
– The default value of the argument imag is zero.
– complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag.
– complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.
• A::A()  Default constructor
 Default argument constructor
• A : : A (int = 0)

• The default argument constructor can be called with either one


argument or no arguments.
• When called with no arguments, it becomes a default constructor.
Destructors
 A destructor is used to destroy the objects that have been
created by a constructor.

• Like constructor, the destructor is a member function whose name


is the same as the class name but is preceded by a tilde.
eg: ~ integer ( ) { }
Destructors

 A destructor never takes any argument nor does it return any value.

 It will be invoked implicitly by the compiler upon exit from the program – or
block or function as the case may be – to clean up storage that is no longer
accessible.

 It is a good practice to declare destructors in a program since it releases


memory space for further use.

 Whenever new is used to allocate memory in the constructor, we should use


delete to free that memory.

You might also like