OOP Material Unit 1 2 3
OOP Material Unit 1 2 3
POP(C) OOP(C++)
In POP, larger programs are divided into In OOP, larger programs are divided into
functions objects.
In POP, most functions share global data In OOP mostly the data is private and only
i.e data move freely around the system functions inside the object can access the
from function to function. data.
In POP, there are no access specifiers. In OOP there are public, private and
protected specifiers.
A function transforms data from one from Objects may communicate with each other
to another. through functions
Data is not hidden easily to access. Data is hidden and can’t access by other
function
POP has no facility like class, abstraction, OOP has facility like class, abstraction,
inheritance, encapsulation, inheritance, encapsulation,
polymorphism..etc polymorphism..etc
Eg ..C, QBASIC, PASCAL are procedure Eg.. C++, JAVA are Object Oriented
oriented language. Language.
Object Oriented Programming
Explain Characteristics of OOP.
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as objects.
3. Data and functions are tied together in the data structure.
4. Data is hidden and can not be accessed by external functions.
5. Objects may communicate with each other through functions.
6. New data and functions can be easily added whenever necessary.
7. Bottom-up approach.
switch (gender)
{
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}
Object Oriented Programming
Output:
Gender is Male
Example
enum year {
Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec
};
// Driver Code
int main()
{
int i;
return 0;
}
Objects: - Objects are basic run-time entities. They contain data and code together. They
may represent a person, a place, a bank account, a table of data, or any item in the
program. Program objects should be chosen such that they match closely with the real
world. Objects take up space in memory. Objects can communicate with one another by
sending messages.
Object Oriented Programming
Example:-
#include <iostream.h>
#include <conio.h>
class test //Class name
{
int data;
public:
void read() //method
{
cout<<"Enter any no:=>";
cin>>data;
}
void show() //method
{
cout<<data<<endl;
}
};
void main()
{
clrscr();
test t; //define object for accessing a class.
t.read();
t.show();
getch();
}
What is visibility modifier OR access specifiers? List out differentiate with proper
example
To provide the facility of security by means of data hiding, is get done by some access
specifies and these access specifies are known as visibility modifiers or access
specifiers.
These visibility modifiers are used to secure the data member and member function of
a class.
There are threes types of visibility modifiers 1. Public 2. Private 3. Protected
Public variables are variables that are visible to all classes.
Private variables are variables that are visible only to the class to which they belong.
Protected variables are variables that are visible only to the class to which they belong,
and any subclasses
Deciding when to use private, protected or public variable is sometimes tricky. You
need to think whether or not an external object (or program), actually needs direct access
to the information. If you do want other objects to access internal data, but wish to
control it, you would make it either private or protected, but provide functions which can
manipulate the data in a controlled way.
Object Oriented Programming
What are the different between class and structure?
Class Structure
A class is way to bind the data and its A structure is a user defined data type
associated functions together. And it allows which is the collection of different of
the data to be hidden from external use. elements who having different Data types.
A class has three access modifiers. A structure has not any access modifier.
Public, Private, Protected
Class keyword is used to declare the class Struct keyword is used declare the
structure.
Class binds both data and member Structure contain only data.
functions.
Syntax: Syntax:
Class <class name> Struct <structure name>
{ {
Private: data type variable1;
Public: data type variable2;
Protected: data type variable2;
}; };
public:
void Get()
{
cout<<"Enter Number:";
cin>>Num;
Object Oriented Programming
}
void Display()
{
cout<<"Square Is:"<<Num*Num;
}
};
void main()
{
Square Obj;
Obj.Get();
Obj.Display();
getch();
}
Explain scope resolution operator with example.
In C, the global version of a variable cannot be accesses from within the inner block.
C++ resolves this problem by introducing a new operator :: called the scope resolution
operator. This can be used uncover a hidden variable.
}
void display()
{
What is friend function? Why we need to write friend function? Explain with
example. Discuss its advantages.
We know that the private members can not be accessed from outside the class. That is,
a non member function cannot have an access to the private data of a class.
For example, consider a case where two classes, manager and scientist, have been
defined. We would like to use a function income_tax ( ) to operate on the object of both
classes. In the situations, C++ allows the common function to be made friendly with both
classes, there by allowing the function to have access to the private data of these classes.
Syntax
Class Abc
{
Public:
………….
………….
friend void xyz(void); //declaration
};
The function declaration should be preceded by the keyword friend.
Characteristics of friend function
It is not in the scope of the class to which it has been declared as friend.
Object Oriented Programming
Since it is not in the scope of the class, it can not be called using the object of that
class.
It can be invoked like a normal function without the help of any object.
Unlike member function, it can not access the member names directly and has to use
an object name and not membership operator with each member name(eg. A.x).
It can be declared either in the public or the private part of a class without affecting its
meaning.
Usually, it has the objects as arguments.
The friend functions are often used in operator overloading.
Example (Data members are private)
#include <iostream.h>
#include <conio.h>
class sample
{
private:
int a;
int b;
public:
void setvalue()
{
a=25;b=40;
}
friend float mean(sample s);
};
float mean (sample s)
{
return float(s.a + s.b)/2.0;
}
void main()
{
clrscr();
sample x;
x.setvalue();
cout << "Mean Value:=> " << mean(x)<<"\n";
getch();
}
A simple example of a friend class.
class A
{
int x =5;
Object Oriented Programming
friend class B; // friend class.
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
Object Oriented Programming
What is Inheritance? Explain Types of Inheritance with example.
The mechanism of deriving a new class from an old one is called inheritance (or
derivation).The old class is referred to as the base class and the new one is called the
derived class or subclass.
Inheritance allows us to define a class in terms of another class, which makes it easier
to create and maintain an application. This also provides an opportunity to reuse the code
functionality and fast implementation time.
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Single Inheritance: - Single Inheritance is method in which a derived class has only one
base class.
Example
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
};
class Cube: public Value
{
public:
int cube()
{ return (val*val*val); }
Object Oriented Programming
};
int main ()
{
Cube cub;
cub.set_values (5);
cout << "The Cube of 5 is::" << cub.cube() << endl;
return 0;
}
Result:
2. Multiple Inheritance:- You can derive a class from any number of base classes. Deriving
a class from more than one direct base class is called multiple inheritance.
Multiple inheritance enables a derived class to inherit members from more than one
parent.
Deriving directly from more than one class is usually called multiple inheritance.
Syntax:-
Class C: Public A, Public B
{
Body of D
Example
class student
{
protected:
int rno,m1,m2;
public:
void get()
{
cout<<"Enter the Roll no :";
cin>>rno;
cout<<"Enter the two marks :";
cin>>m1>>m2;
}
};
class sports
{
protected:
int sm; // sm = Sports mark
public:
void getsm()
{
cout<<"\nEnter the sports mark :";
cin>>sm;
}
};
class statement:public student,public sports
{
int tot,avg;
public:
void display()
{
tot=(m1+m2+sm);
avg=tot/3;
cout<<"\n\n\tRoll No : "<<rno<<"\n\tTotal: "<<tot;
cout<<"\n\tAverage : "<<avg;
}
};
void main()
{
clrscr();
statement obj;
obj.get();
obj.getsm();
obj.display();
getch();}
Output:
Enter the Roll no: 100
Enter two marks
90
80
Ambiguity: - In multiple inheritance the ambiguity arises when same method name is being
used by two derived class and further derivation from these two base classes.
To resolve this ambiguity we are using scope resolution operator.
class M
{
public:
void display()
{
cout<<"vimal \n";
}
};
class N
{
public:
void display()
{
cout<<"Vaiwala\n";
}
}
class P:public M,public N
{
public:
void display(void)
{
M::display();
N::display();
};
int main()
{
clrscr();
P p;
p.display();
getch();
}
Output:
Vimal
Vaiwala
Syntax:-
class A
{
-------
-------
};
class B : visibility_label A
{
-------
-------
};
class C : visibility_label A
{
-------
-------
};
class D : visibility_label A
{
-------
-------
};
Here the visibility_label can be private, protected or public. If we do not specify any
visibility_label then by default is private.
class A
{
public:
int val;
void getvalue(int j)
{
val=j;
}
};
class B : public A
{
public:
void square()
{
cout<<endl<<val*val;
}
};
class C : public A
{
public:
void cube()
{
cout<<endl<<val*val*val;
}
void main()
{
int i;
clrscr();
B b;
C c;
cin>>i;
b.getvalue(i);
b.square();
c.getvalue(i);
c.cube();
getch();
}
Output
2
4
8
4. Multilevel Inheritance: - The mechanism of deriving a class from another ‘derived class’
is known as multilevel inheritance.
It is the inheritance hierarchy wherein subclass acts as a base class for other classes.
Multilevel Inheritance is a method where a derived class is derived from another derived
class.
Example
class A
{
protected:
int x;
public:
Prepared By: Dr.Vimal A. Vaiwala Page 19
Object Oriented Programming
void showA()
{
cout<<"enter a value for x:"<<endl;
cin>>x;
}
};
class B:public A
{
protected:
int y;
public:
void showB()
{
cout<<"enter value for y:";
cin>>y;
}
};
class C:public B
{
public:
void showC()
{
showA();
showB();
cout<<"x*y ="<<x*y;
}
};
void main()
{
C ob1;
ob1.showc();
}
Output
Enter value of x = 12
Enter value of y = 3
X * Y =36
5. Hybrid Inheritance The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.
There could be situations where we need to apply two or more types of inheritance to
design a program.
"Hybrid Inheritance" is a method where one or more types of inheritance are combined together and
used
In figure base class A and class B and C are derived from class A. So that path is called
Hierarchical Inheritance.
Class B and C are the base class for class D. so that path is called multiple inheritance.
because there are more then one base class.
Example:-
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
out<<"Roll no"<<rno<<"\n";
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";
}
};
class sports
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<"sports:"<<score<<"\n";
}
};
class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<"Total Score="<<total<<"\n";
}
int main()
{
clrscr();
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}
OUTPUT
Roll no 123
Marks obtained : part1=27.5
Part2=33
Sports=6
Total score = 66.5
Explain Abstraction
Data abstraction refers to, providing only essential information to the outside word and
hiding their background details i.e. to represent the needed information in program without
presenting the details.
Data abstraction is a programming (and design) technique that relies on the separation of
interface and implementation.
Flexibility in approach:
By hiding data or abstracting details that are not needed for presentation, the programmer
achieves greater flexibility in approach.
Enhanced Security:
Abstraction gives access to data or details that are needed by users and hide the
implementation details, giving enhanced security to application.
Easier Replacement:
Modular Approach:
In object-oriented programming language C++, the abstraction concept helps users to divide
the project application into modules and test each of them separately. Then all modules are
integrated and ultimately tested together. This approach makes the application development
easier.
Definition
It is a Greek term, means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data used
in operation.
A frog can live under water and outside the water also.
Practical example
Ex- For one operator operation ca take different from if operator is working on number ‘+’
than it gives sum of numbers & if this operation is working on string than it will give
concatenation string. This type of behavior is known as operator overloading.
Types of polymorphism
1. Runtime polymorphism
Function Overloading
Single function name can used to handle different number & different types of arguments.
Using single function name to perform different type of task is known as function
overloading.
Using Function overloading we can design a family of function with one function name
but with different argument lists.
The function would perform different operations on the argument list the function call.
The correct function to be invoked is determined by checking the number and type of the
arguments but not on the function type.
A function call first matches the prototype having the same number and type of argument and
then calls the appropriate function for execution. A best match must be unique.
Example
//function prototyping
int volume(int);
double volume(double,int);
long volume(long,int,int);
main()
{
clrscr();
cout<<volume(10) <<"\n";
cout<<volume(2.5,8) <<"\n";
cout<<volume(100L,75,15) <<"\n";
getch();
}
//Function defination
int volume(int s) //cube
{
return (s*s*s);
}
double volume(double r,int h) //cylinder
{
return(3.14519*r*r*h);
}
long volume(long l,int b,int h) //rectangular
{
return (l*b*h);
}
Operator Overloading
Definition:-
C++ permits us to add two variables of user defined types with same syntax that is applied
to the basic types. This means that C++ has the ability to provide the operator with special
meaning for a data type.
i.e. The mechanism of giving such special meaning to an operator is known as operator
overloading.
This is done with the help of a special function, called operator function, which describes
the task. The general form of an operator function is:
Where return type of value returned by the specified operation and op is the operator
overloading being overloaded.
A basic difference between them is that a friend function will have only one argument for
unary operators and two for binary operators, while a member function has no argument for
unary operators and two for binary operators, while a member function has no argument for
unary operators and one for binary operators.
1. Create a class the defines the data type that is to be used in overloading operation.
2. Declare the operator function operator op ( ) in the public part of the class.
3. Define the operator function to implement the required operations.
The overloaded operator must have at least one operand that is of user-defined type.
Overloaded operator follow syntax rules of original operators. They can not be overridden.
we can not use friend function to overload certain operators. = assignment operator, ( )
function call operator, [] subscription operator, class member access operator.
For Unary operator no argument and no return type but in friend function take one
reference argument.
For Binary operator overloaded through a member function, take one explicit argument
and those which are overloaded through a member function take two explicit argument.
For Binary operators, the left hand operand must be an object of the relevant class.
Example:-
class increase
{
private:
int data;
public:
increase()
{
data=0;
}
int display()
{
cout<<data<<endl;
}
void operator++()
{
data++;
}
};
void main()
{
clrscr();
increase i1,i2;
i1.display();
i2.display();
i1++;
i2++;
i1.display();
i2.display();
getch();
}
Friend Function with operator overloading
Friend function may be used in place of member functions for overloading a binary
operator, the difference being that a friend function requires two arguments to be explicitly
passed to it, while a member function requires only one.
Example
class myclass
{
int a;
int b;
public:
myclass(){}
myclass(int x,int y)
{ a=x;
b=y;
}
void show()
{
cout<<a<<endl<<b<<endl;
}
friend myclass operator+(myclass,myclass);
};
myclass operator+(myclass ob1,myclass ob2)
{
myclass temp;
temp.a = ob1.a + ob2.a;
temp.b = ob1.b + ob2.b;
return temp;
}
void main()
{
clrscr();
myclass a(10,20);
myclass b(100,200);
a=a+b;
a.show();
getch();
}
A virtual function is a member function which is declared within a base class and is re-
defined (overridden) by a derived class. When you refer to a derived class object using a
pointer or a reference to the base class, you can call a virtual function for that object and
execute the derived class’s version of the function.
When we use the same function name in both base and derived classes, the function in
base class is declared as virtual using keyword virtual preceding its normal declaration.
When a function is made virtual, C++ determines which function to use at run time based
by making the based on the type of object pointer to by base pointer, rather than the type
pointer. Thus, by making the base pointer to point to different objects, we can execute
different versions of the virtual function.
Example
class Base
{
public:
void display()
{
cout<<"\n Display base";
}
virtual void show()
{
cout<<"\n show base";
}
};
class Derived: public Base
{
public:
void display()
{
cout<<"\n Display Derived";
}
void show()
{
cout<<"\n show derived";
}
};
int main ()
{
clrscr();
Base B;
Derived D;
Base *bptr;
cout<<"\n bptr points to base \n";
bptr=&B;
bptr -> display();//call base version
bptr -> show();//call base version
cout<<"\n\n bptr points to derived \n";
bptr=&D;
bptr -> display();//calls base version
bptr -> show();//calls Derived version
return 0; }
Output
Example
class base
{
public:
//pure virtual function
virtual void show()=0;
};
class derived1 : public base
{
public:
void show()
{
cout<<"\n Derived 1";
}
};
void main()
{
base *b; derived1 d1;
b = &d1;
b->show();
}
Output
Derived1