18CS45 - Ooc - Module 1
18CS45 - Ooc - Module 1
(18CS45)
Module-I
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
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.
7
How to declare a structure in C++ programming?
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.
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
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.
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:
17
Procedure–Oriented Programming
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
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
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.
23
Object Oriented Concept Features
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.
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.
28
Difference between POP(Procedure Oriented Programming) and OOP(Object
Oriented Programming)
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.
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 , 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
35
Structure of C++ Program
36
Structure of C++ Program
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
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++
#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
45
Functions in c++:
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 :
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 main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z; return 0;
}
60
Function Overloading
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.
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
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.
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;
return 0;
}
67
(2) Explicit Type Conversion Also known as ‘Type Casting
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;
return 0;
}
69
Chapter 2:
70
General form of class declaration is:
class class_name
{
access specifier: data ;
access specifier: functions;
};
71
Access specifier By default, data and member
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:
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
76
Accessing members
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.
79
80
this Pointer
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.
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.
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.
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:
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.
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:
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:
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
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:
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
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.
10
Objects and Functions
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;
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
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.=
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[];
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
12
Thank You
12