0% found this document useful (0 votes)
70 views123 pages

18CS45 - Ooc - Module 1

Ppt m1 ooc module 1 me hi to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family

Uploaded by

Jontra
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)
70 views123 pages

18CS45 - Ooc - Module 1

Ppt m1 ooc module 1 me hi to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family members are there in the final output of the day happy birthday to you and your family and friends and family

Uploaded by

Jontra
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/ 123

Object Oriented Concepts

(18CS45)

Module-I

Dr. Sanchari Saha


AP, Dept of CSE,
CMRIT, Bengaluru
Course Objective:
This course (18CS45) will enable students to:
Learn fundamental features of object-oriented language and JAVA
Set up Java JDK environment to create, debug and run simple Java programs.
Create multi-threaded programs and event handling mechanisms.
Introduce event driven Graphical User Interface (GUI) programming using applets and
swings.

Course Outcome:
The student will be able to :
Explain the object-oriented concepts and JAVA.
Develop computer programs to solve real world problems in Java.
Develop simple GUI interfaces for a computer program to interact with users, and to
understand the event-based GUI handling principles using swings
CO-PO and CO-PSO Mapping

P P P P P P P
P P P P P P P P
Modules PO O O O S S S S
Course Outcomes Blooms Level O O O O O O O O
covered 5 1 1 1 O O O O
1 2 3 4 6 7 8 9
0 1 2 1 2 3 4

Explain Object-Oriented
CO1 Concepts in C++ and L2 1,2 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
JAVA.
Develop computer
programs for solution of
CO2 L2 2,3 2 3 3 2 - 2 - - 2 2 - 2 2 - 2 -
real world problems in
Java.
Develop simple GUI
CO3 interfaces for L3 4,5 2 3 3 2 2 2 - - 2 2 - 2 2 - 2 -
interaction with users
Develop Graphical User
CO4 Interface (GUI) with use L3 5 2 3 3 3 2 2 - - 2 2 - 2 2 - 2 -
of Applets and Swings.
Text Book & Reference Book

Textbooks:
1. Sourav Sahay, Object Oriented Programming with C++ , 2nd Ed, Oxford University
Press,2006
2. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007.
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806
2. Herbert Schildt, The Complete Reference C++, 4th Edition, Tata McGraw Hill, 2003.
3. Stanley B.Lippmann, Josee Lajore, C++ Primer, 4th Edition, Pearson Education, 2005.
4. Rajkumar Buyya,S Thamarasi selvi, xingchen chu, Object oriented Programming with java,
Tata McGraw Hill education private limited.
5. Richard A Johnson, Introduction to Java Programming and OOAD, CENGAGE Learning.
6. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies
SYLLABUS

Introduction to Object Oriented Concepts:


A Review of structures,
Procedure–Oriented Programming system,
Object Oriented Programming System,
Comparison of Object Oriented Language with C,
Console I/O,
Variables and reference variables,
Function Prototyping,
Function Overloading.
Class and Objects:
Introduction,
Member functions and data,
Objects and functions.
Chapter 1:
A Review of structures
Structure is a collection of variables of different data types under a
single name. It is similar to a class in that, both holds a collection of data
of different data types.
For example: You want to store some information about a person:
his/her name, citizenship number and salary. You can easily create
different variables name, citNo, salary to store these information
separately.

However, in the future, you would want to store information about


multiple persons. Now, you'd need to create different variables for each
information per person: name1, citNo1, salary1, name2, citNo2, salary2

6
You can easily visualize how big and messy the code would look.
Also, since no relation between the variables (information) would
exist, it's going to be a daunting task.

A better approach will be to have a collection of all related


information under a single name Person, and use it for every
person. Now, the code looks much cleaner, readable and efficient
as well.

This collection of all related information under a single name


Person is a structure.

7
How to declare a structure in C++ programming?

The struct keyword defines a structure type followed by an identifier


(name of the structure).
Then inside the curly braces, you can declare one or more members
(declare variables inside curly braces) of that structure. For example:

struct Person
Here a structure person is
{
defined which has three
char name[50];
members: name, age and
int age;
salary.
float salary;
};

8
When a structure is created, no memory is allocated.

The structure definition is only the blueprint for the creating of


variables. You can imagine it as a datatype. When you define an
integer as below:

int foo;

The int specifies that, variable foo can hold integer element only.
Similarly, structure definition only specifies that, what property a
structure variable holds when it is defined.

9
How to access members of a structure?
The members of structure variable is accessed using a dot (.) operator.

Suppose, you want to access age of structure variable bill and assign it
50 to it. You can perform this task by using following code below:

bill.age = 50;

10
#include <iostream>
using namespace std;
struct Person
{
char name[50];
C++ Program to int age;
assign data to float salary;
members of a };
structure variable int main()
and display it. {
Person p1;
cout << "Enter Full name: ";
cin>>p1.name;
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}
11
#include <iostream>
#include<cstring>// or can use #include<string.h>
using namespace std;
struct Person
{
C++ Program to char name[20];
assign data to int age;
members of a float salary;
structure variable };
and display it. int main()
{
Person p1;
strcpy(p1.name,"ab cd");
p1.age=10;
p1.salary=100;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0;
}

12
#include <iostream>
#include<cstring> // or can use #include<string.h>
using namespace std;
struct Person
{
Here getline() is string name;
used to read int age;
entire line of float salary;
};
input name with
int main()
space {
Person p1;
cout << "Enter Full name: ";
getline(cin, p1.name);
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
cout << "\nDisplaying Information." << endl;
cout << "Name: " << p1.name << endl;
cout <<"Age: " << p1.age << endl;
cout << "Salary: " << p1.salary;
return 0; }
13
Creating new data type using structure

C++ allows us to create our own user-defined aggregate data types. An


aggregate data type is a data type that groups multiple individual
variables together. One of the simplest aggregate data types is the
struct. A struct (short for structure) allows us to group variables of mixed
data types together into a single unit.

Declaring and defining structs

Because structs are user-defined, we first have to tell the compiler what
our struct looks like before we can begin using it. To do this, we declare
our struct using the struct keyword. Here is an example of a struct
declaration:

14
struct Employee
{
short id;
int age;
double wage;
};
This tells the compiler that we are defining a struct named
Employee. The Employee struct contains 3 variables inside of it: a
short named id, an int named age, and a double named wage.
These variables that are part of the struct are called members (or
fields). Keep in mind that Employee is just a declaration -- even
though we are telling the compiler that the struct will have member
variables, no memory is allocated at this time.

15
In order to use the Employee struct, we simply declare a variable of type
Employee:

Employee joe;
This defines a variable of type Employee named joe. As with normal
variables, defining a struct variable allocates memory for that variable.

It is possible to define multiple variables of the same struct type:

Employee joe; // create an Employee struct for Joe


Employee frank; // create an Employee struct for Frank

16
Accessing struct members
When we define a variable such as Employee joe, joe refers to the entire
struct (which contains the member variables). In order to access the
individual members, we use the member selection operator (which is a
period). Here is an example of using the member selection operator to
initialize each member variable:

Employee joe; // create an Employee struct for Joe


joe.id = 14; // assign a value to member id within struct joe
joe.age = 32; // assign a value to member age within struct joe

Employee frank; // create an Employee struct for Frank


frank.id = 15; // assign a value to member id within struct frank
frank.age = 28; // assign a value to member age within struct frank

17
Procedure–Oriented Programming

Procedural programming is a style of programming where procedures


(often called functions, but rarely similar to functions in mathematics)
are the main structural feature of programs, and basic data types are
the main form of representation of data.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,
BASIC, Pascal and C.
In a multi-function program, many important data items are placed as
global so that they may be accessed by all functions. Each function
may have its own local data. If a function made any changes to global
data, these changes will reflect in other functions. Global data are more
unsafe to an accidental change by a function. In a large program it is
very difficult to identify what data is used by which function.

18
Limitations
• The program code is harder to write when Procedural Programming
is employed
• The Procedural code is often not reusable, which may pose the need
to recreate the code if is needed to use in another application
• Difficult to relate with real-world objects
• The importance is given to the operation rather than the data, which
might pose issues in some data-sensitive cases
• The data is exposed to the whole program, making it not so much
security friendly

19
Object Oriented Programming

In OOP we try to model real-world objects.


Most real world objects have internal parts (Data Members) and
interfaces (Member Functions) that enables us to operate them.

Object:
Everything in the world is an object.
An object is a collection of variables that hold the data and functions
that operate on the data.
The variables that hold data are called Data Members.
The functions that operate on the data are called Member Functions.

20
The two parts of an object:
Object = Data + Methods (Functions)
• In object oriented programming the focus is on creating the objects to
accomplish a task and not creating the procedures (Functions).
• In OOPs the data is tied more closely to the functions and does not allow
the data to flow freely around the entire program making the data more
secure.
• Data is hidden and cannot be easily accessed by external functions.
• Compliers implementing OOP does not allow unauthorized functions to
access the data thus enabling data security.

21
• Only the associated functions can operate on the data and
there is no change of bugs creeping into program.
• The main advantage of OOP is its capability to model real
world problems.
• It follows Bottom Up approach in program design.

22
Object Oriented Concept Features

(1)Class: The building block of C++ that leads to Object-Oriented programming is a


Class. It is a user-defined data type, which holds its own data members and member
functions, which can be accessed and used by creating an instance of that class. A
class is like a blueprint for an object.

For Example: Consider the Class of Cars. There may be many cars with different
names and brand but all of them will share some common properties like all of them
will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and
wheels, speed limits, mileage are their properties.

(2)Object: An Object is an identifiable entity with some characteristics and behaviour.


An Object is an instance of a Class. When a class is defined, no memory is allocated but
when it is instantiated (i.e. an object is created) memory is allocated.

23
Object Oriented Concept Features

(3)Encapsulation: In normal terms, Encapsulation is defined as wrapping up of


data and information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the functions that manipulate
them.

Consider a real-life example of encapsulation, in a company, there are different


sections like the accounts section, finance section, sales section etc. The finance
section handles all the financial transactions and keeps records of all the data related
to finance. Similarly, the sales section handles all the sales-related activities and keeps
records of all the sales. Now there may arise a situation when for some reason an
official from the finance section needs all the data about sales in a particular month. In
this case, he is not allowed to directly access the data of the sales section. He will first
have to contact some other officer in the sales section and then request him to give the
particular data. This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name “sales section”.

24
Object Oriented Concept Features

(4)Abstraction: Data abstraction is one of the most essential and important features of
object-oriented programming in C++. Abstraction means displaying only essential
information and hiding the details. Data abstraction refers to providing only essential
information about the data to the outside world, hiding the background details or
implementation.

Consider a real-life example of a man driving a car. The man only knows that pressing the
accelerators will increase the speed of the car or applying brakes will stop the car but he
does not know about how on pressing accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the implementation of accelerator,
brakes etc in the car. This is what abstraction is.

25
Object Oriented Concept Features
(5)Polymorphism: The word polymorphism means having many forms. In simple
words, we can define polymorphism as the ability of a message to be displayed in more
than one form.

A person at the same time can have different characteristic. Like a man at the same time
is a father, a husband, an employee. So the same person posses different behaviour in
different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The behaviour
depends upon the types of data used in the operation.

C++ supports operator overloading and function overloading.


• Operator Overloading: The process of making an operator to exhibit different
behaviours in different instances is known as operator overloading.
• Function Overloading: Function overloading is using a single function name to perform
different types of tasks.

26
Object Oriented Concept Features

Example: Suppose we have to write a function to add some integers, some times there
are 2 integers, some times there are 3 integers. We can write the Addition Method with the
same name having different parameters, the concerned method will be called according to
parameters.

27
Object Oriented Concept Features
(6)Inheritance: The capability of a class to derive
properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important Example: Dog, Cat, Cow can
features of Object-Oriented Programming. be Derived Class of Animal
Base Class.
Sub Class: The class that inherits properties from another
class is called Sub class or Derived Class.
Super Class: The class whose properties are inherited by
sub class is called Base Class or Super class.

Reusability: Inheritance supports the concept of


“reusability”, i.e. when we want to create a new class and
there is already a class that includes some of the code
that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and
methods of the existing class.

28
Difference between POP(Procedure Oriented Programming) and OOP(Object
Oriented Programming)

Sl. no POP OOP

1.
Emphasis is on procedures (functions) Emphasis is on data
2.
Programming task is divided into a Programming task is divided into objects
collectionof data structures and (consisting of data variables and associated
functions. member functions)
3.
Procedures are being separated from data Procedures are not separated from data,
being manipulated instead, procedures and data are combined
together.
4.
A piece of code uses the data to The data uses the piece of code to perform
perform the specific task the specific task

29
5. Data is moved freely from one Data is hidden and can be accessed only by
function to another function using
parameters. member functions not by external function.

6. Data is not secure Data is secure

7. Top-Down approach is used in the Bottom-Up approach is used in program


program design design

8. Debugging is the difficult as the code Debugging is easier even if the code size is
size increases more

30
Console input/ Output in C++

cin: used for keyboard input. It is an object of class istream


cout: used for screen output. It is an object of class ostream
cerr: used for displaying error. It is an object of class ostream

cout is an object of the stdout stream, while cerr is an object of the


stderr stream.
stdout and stderr are different streams, even though they both refer to
console output by default.

cin , cout, cerr require the use of the stream extraction (>>) and
insertion (<<) operators.

31
Extraction operator (>>):
To get input from the keyboard we use the extraction operator and
the object Cin.
Syntax: cin>> variable;
No need for “&” in front of the variable. The compiler figures out the
type of the variable and reads in the appropriate type.

Example:
#include<iostream.h>
void main( )
{
int x; float y;
cin>> x; cin>>y;
}
32
Insertion operator (<<):
To send output to the screen we use the insertion operator on the
object Cout.
Syntax: cout<<variable;
cerr << variable; or cerr << “some string”;
Compiler figures out the type of the object and prints it out
appropriately. Example:
#include<iostream.h>
void main( )
{
cout<<5;
cout<<4.1;
cerr<< “string”;
cout<< ‘\n’;
}
33
Example using cin,cout, cerr

#include<iostream.h>
void main( )
{
int a,b; float k;
char name[30];
cout<< “Enter your name \n”;
cin>>name;
cout<< “Enter two Integers and a Float \n”;
cin>>a>>b>>k;
cerr<<“invalid entry, enter again”;
cin>>a>>b>>k;
cout<< “Thank You, you entered ”;
cout<<a<<b<<k;
}
34
Structure of C++ Program

Header File Declaration Section:


•Header files used in the program are
listed here.
•Header File provides Prototype
declaration for different library functions.
•We can also include user define header
file.
•Basically all pre-processor directives are
written in this section.

35
Structure of C++ Program

Global declaration section: Class declaration section:

•Global Variables are declared here. •Actually this section can be


•Global Declaration may include considered as sub section for the
•Declaring Structure global declaration section.
•Declaring Class •Class declaration and all methods
•Declaring Variable of that class are defined here

36
Structure of C++ Program

Main function: Method definition section


•Each and every C++ program always
starts with main function. •This is optional section.
•This is entry point for all the function. Generally this method was
Each and every method is called used in C Programming.
indirectly through main.
•We can create class objects in the
main.
•Operating system calls this function
automatically.

37
Variables and Reference variables
Variable are used in C++, where we need storage for any value, which
will change in program. Variable can be declared in multiple ways
each with different memory requirements and functioning. Variable is
the name of memory location allocated by the compiler depending
upon the datatype of the variable.

38
Declaration and Initialization
Variable must be declared before they are used. Usually, it is
preferred to declare them at the starting of the program, but in C++
they can be declared in the middle of program too but must be done
before using them.
Example :
int i; // declared but not initialised char c;
int i, j, k; // Multiple declaration

Initialization means assigning value to an already declared variable,


int i; // declaration
i = 10; // initialization

39
Scope of Variables
All the variables have their area of functioning, and out of that boundary
they don't hold their value, this boundary is called scope of the variable.
For most of the cases its between the curly braces, in which variable is
declared that a variable exists, not outside it. we can broadly divide
variables into two main types,

• Global Variables
• Local variables

40
Local Variables

Local variables are the variables which exist only between the
curly braces, in which its declared. Outside that they are
unavailable and leads to compile time error.
Example :
#include <iostream>
int main()
{
int i=10;
if(i<20) // if condition scope starts
{
int n=100; // Local variable declared and initialized
} // if condition scope ends
cout << n; // Compile time error, n not available here
}
41
Global variables
Global variables are those, which are once declared and can be
used throughout the lifetime of the program by any class or any
function. They must be declared outside the main() function. If
only declared, they can be assigned different values at different
time in program lifetime. But even if they are declared and
initialized at the same time outside the main() function, then also
they can be assigned any value at any point in the program.

42
Example :

#include <iostream>
int x; // Global variable declared
int main()
{
x=10; // Initialized once
cout <<"first value of x = "<< x;
x=20; // Initialized again
cout <<"Initialized again with value = "<< x;
}

43
Reference variable in C++

When a variable is declared as reference, it becomes an alternative


name for an existing variable. A variable can be declared as reference by
putting ‘&’ in the declaration.

#include<iostream>
using namespace std;
int main()
{ Output:
int x = 10;
// ref is a reference to x.
int& ref = x; x=
// Value of x is now changed to 20 ref =
ref = 20;
cout << "x = " << x << endl ;
// Value of x is now changed to 30
x = 30;
cout << "ref = " << ref << endl ;
return 0;
}
44
Difference between Pointer variable & Reference Variable

Reference Variable Pointer Variable

References must be initialized Pointer can be initialized at any


when created time
Once reference is assigned with Pointer can point to another object
some variable , it cannot be at any time
changed
We cannot have NULL reference Pointer can be assigned with
NULL value

45
Functions in c++:

Definition: Dividing the program into modules, these modules are


called as functions.

General form of function:


return_type function_name(parameter list)
{ Where,
Body of the function return_type: What is the value to be
} return. Function can written any value
except array.
Components of function:
• Function declaration (or) prototype.
Parameter list:
• Function parameters (formal parameters) List of variables separated by comma.
• Function definition The body of the function(code) is private to
• Return statement that particular function, it cannot be
• Function call accessed outside the function.

46
Function prototyping:
int max(int x, int y); Consider the following
statement:
• It provides the following information to the int max(int x, int y);
compiler.
It informs the compiler that
• The name of the function the function max has 2
• The type of the value returned( default an arguments of the type
integer) integer.
• The number and types of the arguments that The function max( ) returns
must be supplied in a call to the function. an integer value the
• Function prototyping is one of the key compiler knows how many
improvements added to the C++ functions. bytes to retrieve and how
• When a function is encountered, the compiler to interpret the value
returned by the function.
checks the function call with its prototype so
that correct argument types are used.
47
48
Argument passing: The arguments that are passed in a
function call are called actual
Two types arguments.
1. Call by value/pass by value
2. Call by reference/ pass by reference

Call by value:
Call by reference:
• The default mechanism of
parameter passing( argument Here we pass address of actual
passing) is call by value. parameters to the formal
• Here we pass the value of actual parameters.
parameters to formal parameters. Changes made to the formal
• Changes made to the formal parameters will affect actual
parameters will not affect the actual parameters.
parameters.

49
Call by value:

50
Call by reference:

51
Types of Function Prototyping:

52
(1) Function with no argument and no return value :

When a function has no arguments, it does not receive any data from the
calling function. Similarly when it does not return a value, the calling
function does not receive any data from the called function.

Syntax :
Function declaration : void function();
Function call : function();
Function definition :
void function()
{
statements;
}

53
#include <iostream>
using namespace std;
void addition ( )
{
int a, b, r;
cout<<“enter two numbers”;
cin>>a>>b;
r=a+b;
cout<<“result is :”<<r;
}
int main ()
{
addition();
return 0; }

54
(2) Function with arguments but no return value :

When a function has arguments, it receive any data from the


calling function but it returns no values.

Syntax :
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}

55
#include <iostream>
using namespace std;
void addition ( int a, int b)
{
int r;
r=a+b;
cout<<“result is :”<<r;
}
int main ()
{
int a, b;
cout<<“enter two numbers”;
cin>>a>>b;
addition(a,b);
return 0;
}

56
(3) Function with no arguments but returns a value :
There could be occasions where we may need to design functions
that may not take any arguments but returns a value to the calling
function. A example for this is getchar() function it has no
parameters but it returns an integer an integer type data that
represents a character.

Syntax :
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
statements;
return x; }

57
#include <iostream>
using namespace std;
int addition ( )
{
int a, b, r;
cout<<“enter two numbers”;
cin>>a>>b;
r=a+b;
return r;
}
int main ()
{
int r;
r=addition();
cout<<“result is” <<r
return 0; }

58
(4) Function with arguments and return value

Syntax :
Function declaration : int function ( int );
Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}

59
#include <iostream>
using namespace std;

int addition (int a, int b)


{
int r;
r=a+b;
return r;
}

int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z; return 0;
}

60
Function Overloading

Two or more functions having same name but different


argument(s) are known as overloaded functions

61
Function Overloading allows us to have more than one function
having same name but different parameter list, when I say
parameter list, it means the data type and sequence of the
parameters, for example the parameters list of a function
myfuncn(int a, float b) is (int, float) which is different from the
function myfuncn(float a, int b) parameter list (float, int). Function
overloading is a compile-time polymorphism.

sum(int num1, int num2)


sum(int num1, int num2, int num3)
sum(int num1, double num2)

62
#include <iostream>
using namespace std;
class Addition {
public:
int sum(int num1,int num2) {
Example : using return num1+num2;
class concept }
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}

63
Example : 2

#include <iostream> int main(void) {


using namespace std; printData pd;

class printData { // Call print to print integer


public: pd.print(5);
void print(int i) {
cout << "Printing int: " << i << endl; // Call print to print float
} pd.print(500.263);
void print(double f) {
cout << "Printing float: " << f << endl; // Call print to print character
} pd.print("Hello C++");
void print(char* c) {
cout << "Printing character: " << c << endl; return 0;
} }
};

64
Advantages of Function overloading
The main advantage of function overloading is to the improve the
code readability and allows code reusability. In the example 1, we
have seen how we were able to have more than one function for the
same task(addition) with different parameters, this allowed us to add
two integer numbers as well as three integer numbers, if we wanted
we could have some more functions with same name and four or five
arguments.

Imagine if we didn’t have function overloading, we either have the


limitation to add only two integers or we had to write different name
functions for the same task addition, this would reduce the code
readability and reusability.

65
Typecasting in C++
A type cast is basically a conversion from one type to another. There
are two types of type conversion:
(1) Implicit Type Conversion Also known as ‘automatic type
conversion’.
Done by the compiler on its own, without any external trigger from the
user.
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 loss of data.

All the data types of the variables are upgraded to the data type of the
variable with largest data type.

bool -> char -> short int -> int -> unsigned int -> long int -> float ->
double -> long double
66
An example of implicit conversion

#include <iostream>
using namespace std;
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
// y implicitly converted to int. ASCII
// value of 'a' is 97
x = x + y;
// x is implicitly converted to float
float z = x + 1.0;

cout << "x = " << x << endl


<< "y = " << y << endl
<< "z = " << z << endl;

return 0;
}

67
(2) Explicit Type Conversion Also known as ‘Type Casting

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


the user can typecast the result to make it of a particular data type.
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.

68
#include <iostream>
using namespace std;

int main()
{
double x = 1.2;

// Explicit conversion from double to int


int sum = (int)x + 1;

cout << "Sum = " << sum;

return 0;
}

69
Chapter 2:

Class and Objects


• A Class is way to bind(combine) the data and its associated functions
together. it allows data and functions to be hidden.
• When we define a class, we are creating a new abstract data type that
can be created like any other built-in data types.
• This new type is used to declare objects of that class.
• Object is an instance of class.

70
General form of class declaration is:

class class_name
{
access specifier: data ;
access specifier: functions;
};

The keyword class specifies that what follows is an abstract data of


type class_name. The body of the class is enclosed in braces and
terminated by semicolon.

71
Access specifier By default, data and member

Access specifier can be of 3 types: functions declared within a class

Private: are private. Variables declared


Cannot be accessed outside the class. inside the class are called as data
But can be accessed by the member members and functions are called
functions of the class.
as member functions. Only member

Public: functions can have access to data


Allows functions or data to be members and function.
accessible to other parts of the
➢ The binding of functions and data
program.
together into a single class type
Protected: variable is referred as
Can be accessed when we use Encapsulation
inheritance.
72
#include<iostream>
using namespace std;
class student
{
private:
char name[10]; int marks1,marks2;
// private variables
public:
void getdata( ) // public function accessing private members
{
cout<<”enter name, marks in two subjects”;
cin>>name>>marks1>>marks2;
}
void display( ) // public function
{
}
}; // end of class
void main( )
{
student obj1;
obj1.getdata( );
obj1.display( );
}

73
Scope resolution operator (::)
• It is used to define the member functions outside the class.
• Scope resolution operator links a class name with a member
name in order to tell the compiler what class the member
belongs to.
• Used for accessing global data.

Syntax to define the member functions outside the class using Scope
resolution operator:

return_type class_name : : function_name( parameter list)


{
function body
}

74
#include<iostream>
using namespace std;
class student
{
private: char name[10]; // private variables
int marks1,marks2;
public: void getdata( );
void display( );
};
void student: :getdata( )
{
cout<<”enter name,marks in two subjects”;
cin>>name>>marks1>>marks2;
}
void student: :display( )
{
cout<<”name:”<<name<<endl;
cout<<”marks”<<marks1<<endl<<marks2;
}
void main( )
{
student obj1; obj1.getdata( ); obj1.display( );
}

75
Accessing global variables using scope resolution operator (: :)

#include<iostream>
using namespace std;
int a=100; // declaring global variable

In this program, class x


{
the statement public: int a;
::a prints global void f( )
{
variable value a=20; // local variable
of a as 100. cout<<a; // prints value of a as 20
}
};
void main( )
{
x g;
g.f( ); // this function prints value of a(local variable) as 20
cout<<::a; // this statement prints value of a(global variable)
as 100
}

76
Accessing members

Class members(variables(data) and functions) Can be accessed


through an object and dot operator.

Private members can be accessed by the functions which belong to


the same class.
The format for calling a member function is:

Object_name.function_name(actual arguments);

77
Example: accessing private members

#include<iostream>
using namespace std;
class item
{
Private: int a;
public: int b;
};

void main( )
{
item i1,i2;
i1.a=10; // illegal private member cannot be accessed outside
the class
i2.b=20;
cout<<i2.b; // this statement prints value of b as 20.
}

78
Defining member functions
We can define the function inside the class.
We can define the function outside the class.

The member Functions have some special characteristics:


Several different classes can use same function name.
Member function can access private data of the class.
A member function can call another function directly, without
using dot operator.
Defining the function inside the class:
Another method of defining a member function is to replace the
function declaration by actual function definition inside the class.

79
80
this Pointer

• Every object in C++ has access to its own address through an


important pointer called this pointer. The this pointer is an implicit
parameter to all member functions. Therefore, inside a member
function, this may be used to refer to the invoking object.
• Friend functions do not have a this pointer, because friends are
not members of a class. Only member functions have a this pointer.
• Suppose that you create an object named x of class A and class A
has non static member function f( ). If you call the function x.f( ), the
keyword this in the body of f ( ) stores the address of x. A static
member function doesn’t have this pointer.
81
#include<iostream>
using namespace std;
class Test
{
private:
int x;
public:
void setX (int x)
Example use 1: {
When local variable’s // The 'this' pointer is used to retrieve the object’s x,
hidden by the local variable 'x'
name is same as this->x = x;
member’s name }
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
obj.setX(20);
obj.print();
return 0;
}

82
Data Abstraction
Data abstraction refers to providing only essential information to the
outside world and hiding their background details, i.e., to represent the
needed information in program without presenting the details.
Let's take one real life example of a TV, which you can turn on and
off, change the channel, adjust the volume, and add external
components such as speakers, VCRs, and DVD players, BUT you do
not know its internal details, that is, you do not know how it receives
signals over the air or through a cable, how it translates them, and
finally displays them on the screen. Thus, we can say a television
clearly separates its internal implementation from its external
interface and you can play with its interfaces like the power button,
channel changer, and volume control without having any knowledge
of its internals.

83
Abstraction using Classes: We can implement Abstraction in C++
using classes. Class helps us to group data members and member
functions using available access specifiers. A Class can decide which
data member will be visible to outside world and which is not.

Abstraction in Header files: One more type of abstraction in C++ can


be header files. For example, consider the pow() method present in
math.h header file. Whenever we need to calculate power of a
number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually
calculating power of numbers.

84
Abstraction using access specifiers
The members that defines the internal implementation can be marked as private in
a class. And the important information needed to be given to the outside world can
be marked as public. And these public members can access the private members
as they are inside the class.

#include <iostream> void display()


using namespace std; {
cout<<"a = " <<a << endl;
class implementAbstraction cout<<"b = " << b << endl;
{ }
};
private:
int a, b; int main()
public: {
// method to set values of implementAbstraction obj;
// private members obj.set(10, 20);
void set(int x, int y) obj.display();
{ return 0;
a = x; }
b = y;
}

85
Data abstraction provides important advantages −
• Helps the user to avoid writing the low level code
• Avoids code duplication and increases reusability.
• Can change internal implementation of class independently without
affecting the user.
• Helps to increase security of an application or program as only
important details are provided to the user.

86
Overloaded Member Functions
Function overloading is a programming concept where which allows
the programmer to define two or more functions using the same
name. It is possible to overload member functions of a class.
Different ways to Overload a Function
• By changing number of Arguments.
• By having different types of argument.

#include<iostream> void Test: : add (int a, int b)


using namespace std; {
class Test int ans;
{ ans=a+b;
public: void add (int , int ); cout<<”addition =”<<ans;
void add (int ,int, int ); }
};

87
void Test: : add (int a, int b, int c) int main()
{ {
int ans; Test obj;
ans=a+b+c; obj.add(10,20);
cout<<”addition is “ << ans; obj.add(10,20,30);
} return 0;
}

88
Default arguments:

A default argument is a value provided in a function declaration that is


automatically assigned by the compiler if the caller of the function
doesn’t provide a value for the argument with a default value. In case
any value is passed the default value is overridden.

➢ A default argument is checked for type at the time of


declaration and evaluated at the time of call.
➢ We must add defaults from right to left.
➢ We cannot provide a default value to a particular argument in
the middle of an argument list.

89
Example:
int mul (int i, int j=5, int k=10); //legal.
int mul (int i=5, int j); //illegal.
int mul (int i=0,int j, int k=10); //illegal.
int mul (int i=2, int j=5, int k=10); //legal.

Default arguments are useful in situations where some arguments


always have the same value.

90
Rules for using Default Arguments
1. Only the last argument must be given default value. You cannot
have a default argument followed by non-default argument.
sum (int x,int y);
sum (int x,int y=0);
sum (int x=0,int y); // This is Incorrect
2. If you default an argument, then you will have to default all the
subsequent arguments after that.
sum (int x,int y=0);
sum (int x,int y=0,int z); // This is incorrect
sum (int x,int y=10,int z=10); // Correct
3. You can give any value a default value to argument, compatible with its
datatype.

91
// Driver Code
#include <iostream> int main()
using namespace std; {
// Statement 1
// A function with default arguments, cout << sum(10, 15) << endl;
// it can be called with
// Statement 2
// 2 arguments or 3 arguments or 4 arguments.
cout << sum(10, 15, 25) << endl;
int sum(int x, int y, int z = 0, int w = 0)
//assigning default values to z,w as 0 // Statement 3
{ cout << sum(10, 15, 25, 30) << endl;
return (x + y + z + w); return 0;
} }

Output
25
50
80

92
Inline functions:

• whenever function is invoked, first control will move from calling


to called function. Then arguments will be pushed on to the
stack, then control will move back to the calling from called
function.
• This process takes extra time in executing.
• To avoid this, we use inline function.
• When a function is declared as inline, compiler replaces function
call with function code.

93
Inline function cannot be used in the
#include<iostream.h> following situation:
void main( ) • If the function definition is too long or
{ too complicated.
cout<< max(10,20); • If the function is a recursive function.
cout<<max(100,90); • If the function is not returning any value.
getch( ); • If the function is having switch
} statement and goto statement.
inline int max(int a, int b) • If the function having looping constructs
{ such as while, for, do-while.
• If the function has static variables
if(a>b)
return a;
else Output:
return b; 20
} 100

94
friend function and friend class:

One of the important concepts of OOP is data hiding, i.e., a non-


member function cannot access an object's private or protected
data.

But, sometimes this restriction may force programmer to write long


and complex codes. So, there is mechanism built in C++
programming to access private or protected data from non-member
functions.

This is done using a friend function or/and a friend class.

95
friend Function in C++
If a function is defined as a friend function then, the private and protected
data of a class can be accessed using the function.
The complier knows a given function is a friend function by the use of the
keyword ‘friend’. It has to use the object name and dot membership
operator with the member name to access the member names.
For accessing the data, the declaration of a friend function should be
made inside the body of the class (can be anywhere inside class either in
private or public section) starting with keyword friend.
Declaration of friend function in C++
class class_name
{
... .. ...
friend return_type function_name(argument/s);
... .. ...
}
96
Now, you can define the friend function as a normal function to access the
data of the class. No friend keyword is used in the definition.

class className
{
... .. ...
friend return_type functionName(argument/s);
... .. ...
}

return_type functionName(argument/s)
{
... .. ...
// Private and protected data of className can be
accessed from
// this function because it is a friend function of
className.
... .. ...
}

97
Example 1: Working of friend Function

#include <iostream> // friend function definition


using namespace std; int addFive(Distance d)
{
class Distance //accessing private data from non-member
{ function
private: d.meter=5;
int meter; return d.meter;
public: }
//friend function declaration
friend int addFive(Distance); int main()
}; {
Distance D;
cout<<"Distance: "<< addFive(D);
return 0;
}

98
Example 2 : Working of friend Function
#include <iostream>
using namespace std;
class rectangle
{ int main()
private: int h,w; {
public: friend int area(rectangle); rectangle r;
}; cout<<"area: "<< area(r);
return 0;
// friend function definition }
int area(rectangle r)
{
//accessing private data from non-member function
r.h=10;
r.w=5;
int area=r.h*r.w;
return area;
}

99
friend Class in C++
Similarly, like a friend function, a class can also be made a friend of
another class using keyword friend. For example:
When a class is made a friend class, all the
member functions of that class becomes friend ... .. ...
functions. A friend class is a class that can class B;
access the private and protected members of a class A
class in which it is declared as friend. This is {
needed when we want to allow a particular // class B is a friend class of class A
class to access the private and protected friend class B;
members of a class. ... .. ...
}
In this program, all member functions of class B
will be friend functions of class A. Thus, any
class B
member function of class B can access the
{
private and protected data of class A. But,
... .. ... }
member functions of class A cannot access the
data of class B.

10
friend Class Example Program
#include <iostream>
using namespace std;
// forward declaration
class ClassB;
class ClassA int main()
{ private: int numA=12; { ClassB objectB;
// friend class declaration cout << "Sum: " << objectB.add();
friend class ClassB; return 0;
}; }
class ClassB
{ private: int numB=1;
public:
// member function to add numA from ClassA
and numB from ClassB
int add()
{
ClassA objectA;
return objectA.numA + numB;
} };
10
Static data members
Data members of class be qualified as static.
A static data member has certain special characteristics:

• It is initialized to zero when first object is created. No other


initialization is permitted.
• Only one copy of the data member is created for the entire class
and is shared by all the objects of class. no matter how many
objects are created.
• Static variables are normally used to maintain values common to
entire class objects.

10
class item
{ void main( )
public: {
static int count; // static data member item i1,i2,i3;
int number; i1.putdata( );
i2.putdata( );
void getdata(int a ) i3.putdata( );
{ i1.getdata( );
number=a; i2.getdata( );
count++; i3.getdata( );
} i1.putdata( ); // display count after reading data
i2.putdata( );
void putdata( ) i3.putdata( );
{ }
cout<<”count value”<<count<<endl;
}
};

10
Output: In this program, the static variable count
Count value 0 is initialized to zero when objects are
Count value 0 created. Count is incremented whenever
Count value 0 data is read into object. Since three times
Count value 3 getdata( ) is called, so 3 times count value
Count value 3 is created. All the 3 objects will have
Count value 3 count value as 3 because count variable
is shared by all the objects, so all the last
3 statements in main( ) prints values of
count value as 3.

10
Static member functions

Like a static member variable, we can also have static member


functions.

A member Function that is declared as static has the following


properties:
A static member function can have access to only other static members
declared in the same class.
A static member function can be called using the class name, instead of
objects.

Syntax:
class_name : : function_name ;

10
class item
{
int number; void main( )
static int count; {
public: item i1,i2;
void getdata(int a ) i1.getdata(10);
{ i2.getdata(20);
number=a; item::putdata( ); // call static
count++; member function using class name
} with scope resolution operator.
static void putdata( ) }
{
cout<<”count value”<<count; Output:
} Count value 2
};

10
In this program, we have one static data member count, it is
initialized to zero, when first object is created, and one static
member function putdata( ),it can access only static member.

When getdata( ) is called,twice,each time, count value is


incremented, so the value of count is 2.

when static member function putdata( ) is called, it prints value of


count as 2.

10
Objects and Functions

There are 2 cases that occur in relation to objects and functions:

1. Passing object as argument to function


2. Returning object from function

Passing object as argument to function


To pass an object as an argument we write the object name as the
argument while calling the function the same way we do it for other
variables.

function_name(object_name);

10
C++ program to show passing of objects to a function
int main()
#include <iostream>
{
using namespace std;
// Create objects
class Example {
Example E1, E2;
public:
int a;
// Values are initialized for both
objects
// This function will take an object as an
E1.a = 50;
argument
E2.a = 100;
void add(Example E)
cout << “Initial values";
{
cout << "Value of object 1: " << E1.a
a = a + E.a;
<< “ and object 2: " << E2.a ;
}
};

10
//Passing object as an argument to Output:
function add() Initial Values
E2.add(E1);
Value of object 1: 50
// Changed values after passing and object 2: 100
object as argument
cout << "New values "; New values
cout << "Value of object 1: " << E1.a Value of object 1: 50
<< “ and object 2: " << E2.a ;
and object 2: 150
return 0;
}

11
Returning object from function
Syntax: object = return object_name;
#include <iostream>
using namespace std;

class Student { int main()


public: {
double marks1, marks2; Student student1;
};
// Call function
// function that returns object of Student student1 = createStudent();
Student createStudent() {
Student student; return 0;
}
// Initialize member variables of Student
student.marks1 = 96.5;
student.marks2 = 75.0;
Output
// print member variables of Student
cout << "Marks 1 = " << student.marks1 << endl; Marks1 = 96.5
cout << "Marks 2 = " << student.marks2 << endl;
Marks2 = 75
return student;
}
11
In this program, we have created a function createStudent() that returns an object of
Student class.

We have called createStudent() from the main() method

11
Question Bank
Explain the need of Console I/O in C++ Programming language. With an example
program show the usage of C++ Console I/O operation.
Justify how object-oriented programming is better than procedure-oriented
programming
With an example scenario explain the need for structure. Demonstrate creation of new
data type using structure concept
Justify how C++ language is an improvised version of C language
Explain various mechanisms of passing argument to a function. Demonstrate each
possible mechanism with an example program
Explain the usage of reference variable in a program. How reference variable is
different than pointer variable? Write a C++ program to swap two integer values and
display the values before & after swapping.
What kind of error a programmer may face, if for any used function, prototype is
missing? Justify your answer with a sample program. Demonstrate various categories
of function prototype with syntax

11
What makes object-oriented programming preferred over other programming
languages? with suitable real time example explain each of its features.
With an example program show manipulation of data values of a class by
performing explicit address manipulation of object. How this pointer and arrow
operator is helpful in programs?
Write a program with a normal function which adds objects of complex number
class. Declare this normal function as friend function of the complex class
For any class, explain how static data member and static function impacts the
execution of a program. Write C++ program to count the total number of objects
created.

How class is different than object? Write a C++ program to create a class called
employee which contains name, designation and salary as data members and
member functions to read and display details of 10 employees.
Explain how one can bridge two classes using friend function. Write a C++
program to find the sum of two numbers using bridge friend function add ( ).

11
With an example program show the usage of friend class
Write two programs to show the difference in output when static keyword is used for any
member variable and when it is not used.
Write a C++ program with a function to add two points. Each point is made up of two
coordinates. The program should contain the function in which the objects are passed as
argument and the function also returning an object
Whether function overloading is helpful in programming? Justify your answer. Write a C++
program using overloaded function ‘area’ to find area of circle, rectangle & triangle
Consider a program scenario where we have just declared the member function inside a
class. Now, outside the class we want to write the body of the function and invoke the
function inside main( ). Explain with an example program what procedure we should follow
to write the body of the function outside the class and invoke the function.

11
When we define a function, normally the compiler makes a copy of that definition in the
memory and every time the function is called, the compiler jumps to the memory to read
that definition. Consider a scenario where we do not want the compiler to every time jump
to the memory whenever the same function is called. Demonstrate with a program how can
we make the compiler avoid jumping to the memory each time the same function is called.

Write a program which defines a function with three default arguments and call the
function in four ways.

11
Online Study Material Link:
https://www.w3schools.com/java/java_oop.asp
https://www.javatpoint.com/java-oops-concepts
https://www.youtube.com/watch?v=-HafzawNlUo
https://www.youtube.com/watch?v=6T_HgnjoYwM
https://www.youtube.com/watch?v=p3H-53kzMuA

11
Quiz
Which feature of OOPS described the reusability of code?
1.Abstraction
2.Encapsulation
3.Polymorphism
4.Inheritance

Which feature of OOPS derives the class from another class?


1.Inheritance
2.Data hiding
3.Encapsulation
4.Polymorphism

11
Quiz
Which function best describe the concept of polymorphism in programming
languages?
1.Class member function
2.Virtual function
3.Inline function
4.Undefined function

What is the extra feature in classes which was not in the structures?
1.Member functions
2.Data members
3.Public access specifier
4.Static Data allowed

11
Quiz
Which operator overloads using the friend function?
1.*
2.( )
3.->
4.=

Which class cannot create its instance?


1.Parent class
2.Nested class
3.Anonymous class
4.Abstract class

12
Quiz
Which of the following statement of a program is not
right?
1.class teacher{ }; teacher s[5];
2.class teacher{ }s;
3.class teacher{ }; teacher s;
4.class teacher{ }s[];

The combination of abstraction of the data and code is


viewed in________.
1.Inheritance
2.Object
3.Class
4.Interfaces

12
Quiz
Which of the following option best illustrates a friend class?
1.This class can access and manipulate all the private members of
that class which connects to a friend.
2.Friend class can only access and manipulate the protected data
members of that class that connects to a friend.
3.Friend class can't access any data member of another class but
can use its methods
4.Friend class don't have any implementation

What is the process of defining a method in a subclass having same


name & type signature as a method in its superclass?
1. Method overloading
2. Method overriding
3. Method hiding
4. None of the mentioned

12
Thank You

12

You might also like