SlideShare uma empresa Scribd logo
1 de 104
OOP
A U T H O R : A B D U L L A H J A N
U N I T : 8
OBJECT – ORIENTED PROGRAMMING
• object-oriented programming (OOP) is a programming technique in which programs are
written on the basis of objects. An object is a collection of data and function. Object may
represent a person thing or place in real world. In OOP data and all possible functions on
data are grouped together. Object oriented programs are easier to learn and modify.
• Object – Oriented programming is a powerful technique to develop software. It is used to
analyze and design the application in terms of objects. It deals with data and the procedure
that process the data as a single object.
• Some of the most object-oriented languages that have been developed
• C++
• Java
• Smalltalk
• Eiffel
• Clos
FEATURE OF OBJECT ORIENTED
PROGRAMMING
• Objects :
OOP provides the facility of programming based on objects. Objects is an entity
that consists of data and functions.
• Classes :
classes are design for creating objects. OOP provides the facility to design classes
for creating different objects. All properties and function of an object are specified in
classes.
• Real-world modeling:
OOP is based on real-world modeling. As in real world things have properties
and working capabilities similarly objects have data and function. Data represents
properties and functions represent working of objects.
FEATURE OF OBJECT ORIENTED
PROGRAMMING
• Reusability :
OOP provides ways of reusing the data and code. Inheritance is a technique that
allows a programmer to use the code of existing program to create new programs.
• Information hiding:
OOP allows the programmer to hide important data from the user. It is
performed by encapsulation.
• Polymorphism:
polymorphism is an ability of an object to behave in multiple ways.
OBJECTS
• An object represents an entity in the real world such as a person, thing or concept etc.
• An object is identified by its name. an object consists of the following two things:
• Properties : properties are the characteristics of an object
• Functions : function are the action that can be performed by an object.
• Example :
• Some example of objects of different types are as follows:
Physical objects
vehicles such as car, bus , truck etc;
Electrical components
OBJECTS
Element of computer-user environment:
windows
menus
graphics objects
mouse and keyword
User defined data types:
time
angles
PROPERTIES OF OBJECT
• The characteristics of an object are known as its properties' or attributes. Each object has its own
properties. These properties can be used to describe the object. For example the properties of an
object Person can be as follows:
• Name
• Age
• Weight
the properties of an object car can be as follow
• Color
• Price
• Model
• Engine power
PROPERTIES OF OBJECT
• The set of values of the of the attribute of a particular object is called its state. It means
that the state of an object can be determined by the value of its attribute. The
following figure shows the value of the attribute of an object Car.
FUNCTIONAL OBJECT
• An object can perform different tasks and actions. The actions that can be performed
by an object are known as functions or methods. For example the object car can
perform the following functions:
• Start
• Stop
• Accelerate
• Reverse
The set of all function of an object represent the behavior of the object. It means that the
overall behavior of an object can be determined the list of functions of that object.
FUNCTIONAL OBJECT
Start
Stop
Accelerate
Rename
car
CLASSES
• A collection of objects with same properties and functions is known as class. A class is
used to define the characteristics of the objects. It is used as a model for creating
different objects of same type. For example a class person can be used to define the
characteristics and functions of a person. It can be used to create many objects of
type. Person such as all, Usman , Abdullah etc. all objects of person class will have
same characteristics and functions. However the values of each object can be different.
The value are of the objects are assigned after creating an object.
• Each object of a class is known as an instance of the class. For example, Ali, Usman and
Abdullah are three instance of a class Person, similarly , mybook and your book can be
two instance of a class Book
CLASSES
• Declaring a class
• A class is declared in the same way as a structure is declared. The keyword class is used to
declare a class. A class declaration specifies the variable and functions that are common to
all objects of that class. The variable declared in a class are known as member variable or
data members. The functions declared in a class are called member functions.
• Syntax:
• The syntax of declaring a class is as follows:
• Class identifier
• {
• Body of the class
• };
CLASSES
• Class :: it is the keyword that is used to declared a class
• Identifier :: it is the name of the class. The rules for class name are same as the rules for
declaring a variable.
• The class declaration always ends with semi colon. All data members and members
functions are declared within the braces known as body of the class.
• Example :
• Class test
• {
• Int n;
• Char c;
• Float x;
• };
• The above class only contains data member in it. A class may contain both data members
and member functions.
ACCESS SPECIFIER
The commands that are used to specify the access level of class members are known as
access specifiers. Two most important access specifier are as follows
THE PRIVATE ACCESS SPECIFIER
• The private access specifier is used to restrict the use of class member within the class.
Any member of the class declared with private access specifier can only be accessed
within the class. It cannot be accessed from outside the class. It is also the default
access specifier.
• The data members are normally declared with private access specifier. It is because the
data of an object is more sensitive. The private access specifier is used to protect data
member from direct access from outside the class. These data member can only be
used by the functions declared within the class.
THE PUBLIC ACCESS SPECIFIER
• The public access specifier is used to allow the user to access a class member within
the class as well as outside the class. Any member of the class declared with public
access specifier can be accessed from anywhere in the program
• The member functions are normally declared with public access specifier. It is because
the users access functions of an object from outside the class. The class cannot be
used directly if both data member and member functions are declared as private.
private:
Int a;
Char c;
Float x;
Public:
Show();
Input();
test
Outside the class
• The above figure shows that data members a,c and x of class Test cannot be accessed
from outside the class because they are declared with private access specifier. The
member function show() and input() are accessible from outside the class because they
are declared with public access specifier. The data members are accessed and
manipulated indirectly though member functions.
CREATING OBJECTS
• An object is created in the same way as other variables are created. When an object of
a class is created the space for all data member defined in the class is allocated in the
memory according to their data types. An object is also known as instance. The process
of creating an object of a class is also called instantiation
• Syntax:
• The syntax of creating an object of a class is as follow:
• Class_name object_name;
• Char_name it is the name of the class whose type of object is to be created
• Object_name it is the name of the object to be created. The rules for object
are same as the rules for declaring a variable.
EXAMPLE
• Test obj;
• The above example declares an object obj of type test. The object contains all data
members that are defined in class Test.
EXECUTING MEMBER FUNCTION
• An object of a particular class contains all data members as well as member functions
defined in that class. The data member contains the value related to the object. The
member functions are used to manipulate data members. The member functions can be
executed only after creating an object.
• Syntax:
• The syntax of executing member functions is as follow
• Object_name.function();
• Example :
• Test obj;
• Obj.input();
• Write a program that declare a class with one integer data member and two member functions in() and out() to
input and output data in data member.
• #include<iostream>
• Using namespace std;
• Class test {
• Private :
• Int n;
• Public :
• Void in(){
• Cout<<“enter a number”;
• Cin>>n;
• }
• Void out()
• {
• Cout<<“the value of n=“<<n;
• };
• Void main(){
• Test obj;
• Obj.in();
• Obj.out();
• Getch();
• }
• Write a class marks with three data member to store three marks. Write three members functions in() to input marks, sum() to
calculate and return the sum and avg() to calculate and return the average marks.
• Class marks{
• Private:
• Int a,b,c;
• Public:
• Void in(){
• Cout<<“enter three marks”;
• Cin>>a>>b>>c;
• }
• Int sum(){
• Return (a+b+c)/3.0;
• }
• };
• Void main(){
• Mark m;
• Int s;
• Float a;
• M.in();
• S = m.sum();
• A = m.avg();
• Cout<<“sum = “<<s<<endl;
• Cout<<“average =“<<a;
• Getch();
• Return 0;
• Write a class circle with one data member radius. Write three member functions get_radius() to set
radius value with parameter value area() to display radius and circum() to calculate and display
circumference of circle.
• Class circle{
• Private:
• Float radius;
• Public :
• Void get_radius(float r)
• {
• Radius = r;
• }
• Void area() {
• Cout<<“area of circle “<<3.14<<“radius”<<radius;
• }
• Void circum(){
• Cout<<“circumference of circle”<<2*3.14*radius*radius;
• }
• Void circum(){
• Cout<<“circumference of circle”<<2*3.14*radius;
• }
• };
• Int main(){
• Circle c1;
• Float rad;
• Cout<<“enter radius”;
• Cin>>rad;
• C1.get_radius(rad);
• C1.area();
• C1.cirum();
• Getch();
• }
• Write a class book with three data member bookid , pages and price. It also contains the
following member function:
• The get() function is used to input values
• The show() function is used to display values
• The set() function is used to set the values of data members using parameters
• The getprice() function is used to return the value of price.
• The program should create two object of the class and input values for these objects
• The program displays the detail of the most costly book.
• Class book{
• Private:
• Int bookid , pages ;
• Float price;
• Public :
• Void get()
• {
• Cout<<“enter book id”;
• Cin>>bookid;
• Cout<<“enter pages”;
• Cin>>pages;
• Cout<<“enter price”;
• Cin>>price;
• }
• Void show(){
• Cout<<“bookid”<<bookid<<endl;
• Cout<<“pages=“<<pages<<endl;
• Cout<<“price=“<<price<<endl;
• }
• Void set(int id, int pg, float pr)
• {
• Bookid = id;
• Pages = pg;
• Price = pr;
• }
• Int getprice()
• {
• Return price;
• }
• };
• Int main(){
• Book b1, b2;
• B1.get();
• B2.set(2,320,150,75);
• Cout<<“ the detail of most costly book is as follow”<<endl;
• If(b1.getprice() > b2.getprice())
• B1.show();
• Else
• B2.show();
• Getch();
• }
HOW ABOVE PROGRAM WORK
• The above program create two objects of class Book. When two or more objects of the
same class are created each object contains its own values in the memory. The data
members of each object are separate to store the value of a particular object. However
the members functions of the class are created only once in the memory. These
member functions are shared by all objects of the class.
Bookid
Pages
price
Bookid
Pages
Price
1
Get()
Show()
Set()
Getprice()
250
125 20
2
320
150 75
• Write a class Result that contains roll no , name, and marks of three subjects. The
marks are stored in an array of integers. The class also contains the following member
functions.
• The input() function is used to input the values in data members
• The show() functions is used to displays the value of data members
• The total() function returns the total marks of a student
• The avg() function return the average marks of a student
• The program should create an object of the class and call the member functions
Class result{
Private :
Int rno, marks[3];
Char name[50];
Public:
Void input(){
• Cout<<“enter roll no”;
• Cin>>rno;
• Cout<<“enter name”;
• Gets(name);
• For(int I = 0; i<3 ; i++)
• {
• Cout<<“enter marks[“<<i<<”]:”;
• Cin>>marks[i];
• }
• }
• Void show(){
• Cout<<“roll no = ”<<rno<<endl;
• Cout<<“name =“<<name<<endl;
• For(int I = 0; i<3 ; i++)
• Cout<<“marks [“<<i<<”]:”<<marks[i]<<endl;
• }
• Int total(){
• int t = 0;
• For(int I = 0; i<3; i++)
• t = t + marks[i];
• Return t;
• }
• Float avg(){
• Int t = 0;
• For(int I = 0; i<3; i++)
• T = t+marks[i];
• Return t/3.0;
• }
• };
• Void main(){
• Result r;
• R.input();
• R.show();
• Cout<<“n total marks =“<<r.total()<<endl;
• Cout<<“average marks = “<<r.avg()<<endl;
• Getch();
• }
DEFINING MEMBER FUNCTIONS
OUTSIDE CLASS
• The member function of a class can also be defined outside the class. The declaration of
member functions is specified within the class and function definition is specified outside
the class. The scope resolution operator :: is used in function declarator if the function is
defined outside the class.
• Syntax:
• The syntax of defining member function outside the class is as follows:
• Return_type class_name :: function_name(parameter)
• {
• Function body
• }
• Write a class array that contains an array of integers to store five values. It also contains the
following member functions:
• The fill() function is used to fill the array with values from the user.
• The display() function is used to display the value of array.
• The max() function shows the maximum values in the array.
• The min() function shows the minimum value in the array.
• All member function should be defined outside the class
class array{
Private:
Int a[5];
Public:
Void fill();
Void display();
Int max();
Int min();
};
• Void array :: fill(){
• For(int I = 0; i<5;i++)
• {
• Cout<<“enter a[“<<i<<”];
• Cin>>a;
• }
• }
• Void array :: display()
• {
• For(int I = 0; i<5;i++)
• Cout<<“a[“<<i<<”]:”<<a[i]<<endl;
• }
• Int array::max(){
• Int m = a[0];
• For(int I = 0; i<5;i++)
• If(m < a[i])
• M = a[i];
• Return m;
• }
• Int array :: min(){
• Int m = a[0];
• For(int I = 0; i<5; i++)
• If(m>a[i])
• M = a[i];
• Return m;
• }
• Void main(){
• Array arr;
• Arr.fill();
• Cout<<“you entered the following values:”<<endl;
• Arr.display();
• Cout<<“maximum value =“<<arr.max()<<endl;
• Cout<<“maximum value = “<<arr.min();
• Getch();
• }
CONSTRUCTOR
• A type of member function that is automatically executed when an object of that class
is created is known as constructor. The constructor has no return type and has same
name that of class name. The constructor can work as a normal function but it cannot
return any value. It is normally defined in classes to initialize data member
• Syntax:
• The syntax of declaring constructor is as follow:
• Name(){
• Constructor
• }
• Write a class that displays a simple message on the screen whenever an object of that
class is created
• Class hello{
• Private:
• Int n;
• Public:
• Hello(){
• Cout<<“object created …”<<endl;
• }
• };
• Void main(){
• Hello x,y,z;
• Getch();
• }
• Write a class that contains two integer data members which are initialized to 100 when an object is
created. It has a member function avg that displays the average of data members.
class number {
Private:
Int x,y;
Public :
Number(){
X = y = 100;
}
Void avg(){
Cout<<“x= “<<x<<endl;
Cout<<“y=“<<y<<endl;
Cout<<“average = “<<(x+y)/2<<endl;
}
};
Int main(){
Number n;
n.avg();
Getch();
}
USER DEFINED CONSTRUCTOR/EXPLICIT
CONSTRUCTOR
• When users define constructor in class for their own purpose. Especially for initialization of variables,
then such type of constructor are called user defined constructors.
• When constructor is declared for a class the compiler no longer provides an implicit default
constructor. So the objects should be declared according to the constructor prototype that have been
defined for the class.
• Class Cexample {
• Public:
• Int a,b,c;
• Cexample (int n, int m)
• {
• A = n;
• B = m;
• }
• Int multiply(){
• C = a*b;
• Return c;
• }
• };
• Int main(){
• Cexample Cobj(50,10);
• Int result = Cobj.multiply();
• Cout<<“multiplication results is :”<<result;
• Getch();
• Return 0;
• }
• Output ::
• Multiplication result is : 5000
PASSING PARAMETER TO
CONSTRUCTOR
• The method of passing parameter to a constructor is same as passing parameter to
normal function. The only difference is that the parameter are passed to the
constructor. When the object is declared. The parameter are written in parenthesis
along with the object name in declaration statement.
• Syntax:
• The syntax of passing parameter to constructor is as follow:
• Type object_name(parameters);
• Example :
• Class student{
• Private:
• Int marks;
• Char grade;
• Public:
• Student (int m, char g){
• Marks = m;
• Grade = g;
• }
• Void show(){
• Cout<<“marks = “<<marks<<endl;
• Cout<<“grade =“<<grade<<endl;
• }
• };
• Void main(){
• Student s1(730,’A’), s2(621,’B’);
• Cout<<“record of student 1:”<<endl;
• S1.show();
• Cout<<“record of student 2:”<<endl;
• S2.show();
• Getch();
• Return 0;
• }
Write a class TV that contains attribute of Brand Name Model and Retail Price. Write a method to display
all attribute and a method to change the attribute. Also write a constructor to initialize all the attribute.
Class Tv
{
Public:
Tv(char Brand[], char Mod[], float Price);
Void change(char Brand[], char Mod[], float price);
Void display();
Private:
Char BrandName[20];
Char Model[10];
Float Retailprice;
};
Tv :: Tv(char Brand[], char Mod[], float price)
{
Strcpy(BrandName,Brand);
Strcpy(Model, Mod);
RetailPrice = Price;
}
• Void Tv :: Change(Char Brand[], char Mod[], float Price)
• {
• Strcpy(BrandName, Brand);
• Strcpy(Model, Mod);
• RetailPrice = Price;
• }
• Void Tv :: Display()
• {
• Cout<<“Brand Name: ”<<BrandName<<endl;
• Cout<<“Model:”<<Model<<endl;
• Cout<<“Price:”<<RetailPrice<<endl;
• }
• Void main(){
• Tv Test(“Sony”, “HDTV”, “25000”);
• Cout<<“Displaying the object …”<<endl;
• test.display();
• Test.Change(“Toshiba”,”STDV”,220000);
• Cout<<“displaying object after change…”<<endl;
• Test.display();
• Getch();
• }
Output
Displaying the object….
Brand Name: Sony
Model : HDTV
Price : 25000
Displaying object after change….
Brand Name : Toshiba
Model : SDTV
Price : 22000
CONSTRUCTOR OVERLOADING
• The process of declaring multiple constructor with same name but different parameter
is known as constructor overloading. The constructor with same name must differ in
one of the following ways
• Number parameter
• Type of parameter
• Sequence of parameter
• Class over{
• Private:
• Int num;
• Char ch;
• Public:
• Over(){
• Num = 0;
• Ch = ‘x’;
• }
• Over (int n , char c){
• Num = n;
• Ch = c;
• }
• Void show(){
• Cout<<“num = “<<num<<endl;
• Cout<<“ch =“<<ch<<endl;
• }
• };
• Int main(){
• Over first, second(100,’p’);
• Cout<<“the contents of first”<<endl;
• First.show();
• Cout<<“the contents of second”<<endl;
• Second.show();
• Getch();
• }
Output
The content of first :
Num = 0
Ch = x
The contents of second
Num = 100
Ch = p
DEFAULT COPY CONSTRUCTOR
• A type of constructor that is used to initialize an object with another object of the
same type is known as default copy constructor. Its name is “default copy constructor”
because it is available by default in all classes. The user does not need to write this
constructor. It accepts a single object of the same type as parameter. The parameter
for default copy constructor can be given in parenthesis or using assignment operator.
• Syntax:
• Class_name object_name(parameter); OR
• Class_name object_name = parameter;
• Class Book{
• private:
• Int pg,pr;
• Char title[50];
• Public:
• Void get(){
• Cout<<“enter title :”;
• Gets(title);
• Cout<<“enter pages :”;
• Cin>>pg;
• Cout<<“enter price :”;
• Cin>>pr;
• }
• Void show(){
• Cout<<“title :”<<title<<endl;
• Cout<<“pages :”<<pg<<endl;
• Cout<<“Price :”<<pr<<endl;
• }
• };
• Int main(){
• Book b1;
• B1.get();
• Book b2(b1);
• Book b3 = b1;
• Cout<<“the detail of b1:”<<endl;
• B1.show();
• Cout<<“the detail of b2 :”<<endl;
• B2.show();
• Cout<<“the detail of b3 :”<<endl;
• B3.show();
• Getch();
• Return 0;
• }
Ouput
Enter title : visual programming
Enter pages : 637
Enter price : 200
The detail of b1:
Title : visual Programming
Pages : 637
Price : 200
The detail of b2 :
Title : visual programming
Pages : 637
Price : 200
The detail of b3
Title : visual programming
Pages : 637
Price : 200
DESTRUCTOR
• A type of member function that is automatically executed when an object of that class
is destroy is known as destructor. The destructor has no return type and its name is
same as class name. the constructor cannot return any value. It also cannot accept any
parameters . The constructor name is preceded by tilde sign ~ ,
• syntax:
• ~name(){
• Destructor body
• }
• Example :
• Class test{
• Private:
• Int n;
• Public:
• Test()
• {
• Cout<<“object created ….”<<endl;
• }
• ~test(){
• Cout<<“object destroyed ….”<<endl;
• }
• };
• Int main(){
• Test a, b;
• Getch();
• }
Output
Object created …
Object created …
Object destroyed…
Object destroyed ….
FRIEND FUNCTION
• A type of function that is allowed to access the private and protected member of a
particular class from outside the class is called friend function. Normally the private
and protected member of any class cannot be accessed from the outside the class. In
some situations a program may require to access these member. The use of friends
functions allow the user to access these members.
• Example:
• Class B;
• Class A{
• Private :
• Int a;
• Public:
• A()
• {
• A = 10;
• }
• Friend int show(A,B);
• };
• Class B{
• Private :
• Int b;
• Public :
• B(){
• B = 20;
• }
• Friend int show(A,B);
• };
• Int show(A x, B y){
• Int r;
• R = x.a + y.b;
• Cout<<“the value of class a object =“<<x.a<<endl;
• Cout<<“the value of class b object”<<y.b<<endl;
• Cout<<“the sum of both values =“<<endl;
• }
• Int main(){
• A obj1;
• B obj2;
• Show(obj1,obj2);
• Getch();
• }
FRIEND CLASS
• A type of class all of whose member functions are allowed to access the private and protected
members of a particular class is called friend class.
• Example :
• Class A{
• Private:
• Int a,b;
• Public:
• A(){
• a= 10;
• b= 20;
• }
• Friend class B;
• };
• Class B{
• Public:
• Int showA(A obj){
• Cout<<“the value of a :”<<obj.a<<endl;
• }
• Int showB(A obj)
• {
• Cout<<“the value of b:”<<obj.b<<endl;
• }
• };
• Int main(){
• A x;
• B y;
• y.showA(x);
• y.showB(x);
• Getch();
• }
INHERITANCE
• A programming technique that is used to reuse an existing class to build a new class is
known as inheritance. The new class inherits all the behavior of the original class. The
existing class that is reused to create a new class is known as super class, base class or
parent class. The new class that inherits the properties and functions of an existing
class is known as subclass, derived class or child hierarchy.
• Inheritance is one of the most powerful features of object oriented programming. The
basic principle of inheritance is that each subclass shares common properties with the
class from which it is derived.
EXAMPLE
• Suppose we have a class named vehicle. The subclass of this class may share similar
properties such as wheels and motor etc. additionally a subclass may have its own
particular characteristics for example a subclass Bus may have seats for people but
another subclass Truck may have space to carry goods.
vehicle
Bus motorcycle
truck
ADVANTAGES
Reusability :
• Inheritance allows the developer to reuse existing code in many situations. A class
be created once and it can be reused again and again to create many sub classes.
Save time and effort :
• Inheritance saves a lot of time and effort to write the same classes again. The
reusability of existing classes allows the program to work only on new classes.
Increase program structure and reliability :
• A super class is already compiled and testing properly. This class can be used in a
application without compiling it again. The use of existing class increase program
reliability.
CATEGORIES OF INHERITANCE
• Single inheritance :
• A type of inheritance in which a child class is derived from the single parent class is
known as single inheritance. The child class in this inheritance inherits all data
members and member functions of the parent class. It can also add further
of its own.
parent
child
MULTIPLE INHERITANCE
• A type of inheritance in which a child class is derived from multiple parent classes is
known as multiple inheritance. The child class in this inheritance inherits all data
members and member function of all parent classes. It can also add further capabilities
of its own.
Parent 1
child
Parent 2
PROTECTED ACCESS SPECIFIER
• It allow a protected data member to be accessed from all derived classes but not from
anywhere else in the program. It means that child class can access all protected data
member of its parent class.
SPECIFYING A DERIVED CLASS
• The process of specifying derived class is same as specifying simple class. Additionally the
reference of parent is specified along with derived class name to inherit the capabilities of
parent class.
• Syntax:
• The syntax of specifying a derived class is as follow
• Class sub_class : specifier parent_class
• {
• Body of the class
• };
• Class it is the keyword that is used to declared a class
• Sub_class it is name of derived class
• : it create a relationship b/w derived class and super class
• Specifier it indicates the type of inheritance. It can be private , public or protected.
• Parent_class it indicate the name of parent class that is being inherit
• Example :
• Class move{
• Protected:
• Int position;
• Public:
• Move(){
• Position = 0;
• }
• Void forward(){
• Position++;
• }
• Void show(){
• Cout<<“Position =“<<position<<endl;
• }
• };
• Class move2 : public move {
• Public :
• Void backward(){
• Position--;
• }
• };
• Int main(){
• Move2 m;
• M.show();
• M.forward();
• M.show();
• M.backward();
• M.show();
• Getch();
• }
POLYMORPHISM
• Polymorphism is the ability to use an operator or function in multiple ways.
Polymorphism gives different meaning or functionality to the operator or functions.
Poly refer to many , signifies(meaning) that there are many uses of these operator and
functions.
• In C++ polymorphism can be achieved by one of the following concepts.
• Function overloading
• Operator overloading
• Virtual function
POLYMORPHISM
• The word polymorphism is a combination of two words poly and morphism. Poly
means many and morphism means form. In object-oriented programming
polymorphism is the ability of objects of different types to respond to function of the
same name. the user does not have to known the exact type of the object in advance.
The behavior of the object can be implemented at run time. It is called late binding or
dynamic binding . Polymorphism is implemented by using virtual functions.
• Pointer to objects:
• A pointer can also refer to an object of a class. The member of an object can be
accessed through pointers by using the symbol ->. The symbol is known as member
access operator.
POLYMORPHISM
• Syntax:
• Ptr -> member
• Ptr it is the name of the pointer that reference an object
• -> it is the member access operator that is used to access a member of object.
• Member it is name of the class member to be accessed.
• Example:
• Class test{
• Private :
• Int n;
• Public :
• Void in(){
• Cout<<“enter number”;
• Cin>>n;
• }
• Void out(){
• Cout<<“the value of n = “’<<n;
• }
• };
• Int main(){
• Test *ptr;
• Ptr = new test;
• Ptr -> in();
• Ptr -> out();
• getch();
• How above example work?
• The above program declare a class test and a pointer ptr of type test. The pointer can
refer to an object of the class. The new operator creates an object in the memory and
stores the address in ptr. The program then uses the pointer to call the member
functions of the object being referenced by the pointer. The symbol -> is used to
access the member of any object through pointer. The user of dot operator with
pointer to access any member is invalid.
• Write a class that contains an attribute name, a function to input and a function to display name. creates array of pointer in which each
element refers to an object of the class.
• Class person
• {
• Private:
• Char name[50];
• Public:
• Void get(){
• Cout<<“enter your name”;
• Cin>>name;
• }
• Void show(){
• Cout<<“your name =“<<name<<endl;
• }
• };
• Int main(){
• Person *ptr[5];
• Int I;
• For(I = 0; i<5; i++){
• Ptr[i] =new person;
• Ptr[i] ->get();
• }
• For(i=0; i<5; i++)
• Ptr[i] -> show();
• Getch();
• }
OPERATOR OVERLOADING
• The process of defining additional meanings of operators is known as operator
overloading. It enables an operator to perform different operations depending on the
type of operands. It also enables the operators to process the user-defined data types.
• The basic arithmetic operators such as +,-,* and / normally work with basic types such
as int , float and long etc.
OVERLOADING AN OPERATOR
• An operator can be overloaded by declaring a special member function in the class. The
member function uses the keyword operator with the symbol of operator to be overloaded.
• Syntax:
• The syntax of overloading an operator is as follow
• Return_type operator op()
• {
• Function body
• }
• Example :
• Void operator ++()
• {
• Function body;
• }
OVERLOADING ++ OPERATOR
• The increment operator ++ is a unary operator. It works with single operand. It
increase the value of operand by 1. it only works with numerical values by default. It
can be overloaded to enable it to increase the values of data members of an object in
the same way.
• Program :
• Write a program that overload increment operator to work with user-defined objects.
• Class count
• {
• Private:
• Int n;
• Public:
• Count(){
• N = 0;
• }
• Int show(){
• Cout<<“n=“<<n<<endl;
• }
• Int operator ++(){
• N = n+1;
• }
• };
• Int main(){
• Count obj;
• Obj.show();
• ++obj;
• Obj.show();
• Getch();
• Return 0;
VIRTUAL FUNCTION
• Virtual means existing in effects but not in reality. A type of function that appears to
exist in some part of a program but does not exist really is called virtual function.
Virtual function are used to implement polymorphism. They enable the user to execute
completely different function by the same function call.
• A virtual function is defined in the parent class and can be overridden in child classes.
It is defined by using the keyword virtual.
VIRTUAL FUNCTION
• A virtual function is a special type of member function. It is defined in the base class
and may be redefined in any class derived from this base class. Its name in the base
class and in the derived classes remain the same. Its definition in these classes may be
different.
• The virtual function in derived class is executed through the pointer of the public base
class.
• A virtual function is declared by writing the word virtual before function declaration in
the base class. The function with the same name are declared in the derived classes.
• Example:
• Class a{
• Public:
• Virtual void show(){
• Cout<<“parent class a…”<<endl;
• }
• };
• Class b : public a{
• Public:
• Void show(){
• Cout<<“child class b…..”<<endl;
• }
• };
• Class c : public a {
• Public:
• Void show()
• {
• Cout<<“child class c…”<<endl;
• }
• };
• Int main(){
• A obj1;
• B obj2;
• C obj3;
• A *ptr;
• Ptr = &obj1;
• Ptr->show();
• Ptr = &obj2;
• Ptr -> show();
• Ptr = &obj3;
• Ptr->show();
• Getch();
• }
Ouput
Parent class A……
Child class b……
Child class C….
FILE
HANDLING
A U T H O R : : A B D U L L A H J A N
INTRODUCTION
• A file is a collection of related records that are permanently stored in secondary
storage.
• File handling is an important feature of C++ language. This unit describe different
types of files such as text files and binary files and describe how different operation
like opening reading writing and closing are performed on files.
FILE HANDLING
• The combination of character words and record are called files. Suppose we have a file
on the disk and want to open it then reading from or writing into the file before
closing it will be termed as handling files. The basic steps involved in the file handling
are :
• Opening file
• Reading and writing a file
• Closing file
TYPES OF FILE
• Text files: are those files that store data in text format which is readable by humans
example of text file is the c++ source program which can be read by human.
• Binary files: store data in binary format which is not readable by humans but readable
by computers. Binary files are directly processed by computer. Binary files are normally
used to store large data files. They take less space to store data as compared to text
files. Forexample an integer having length of six digits will take six bytes to
accommodate in a text file while in binary files they only two bytes, the best example
of binary file is the object of a c++ source file that is generated by the computer of
c++.
OPENING FILE
• To open a file the function open() is used whose syntax is:
• Myfile.open(filename);
• Here myfile is an internal variable actually an object used to handle the file whose
name is written in the parenthesis. To declare this variable the following statement is
used :
• Ifstream myfile ;
MODE OF OPENING A FILE
• While opening a file we tell the compiler what we want to do with it i.e we want to
read the file or write into the file or want to modify it. In order to open a file in any
desired mode the member function open() should take mode as an argument along
with the file name.
• Its general syntax is below:
• Open (filename, mode);
• Here file name representing the name of the file to be opened, and mode is an
optional parameter with a combination of the following flags.
MODE OF OPENING A FILE
Ios :: in open for input operation
Ios :: out Open for output operation
Ios :: binary Open in binary mode
Ios :: ate Set the initial position at the end of the file. If
this flags is not set to any value the initial
position is the beginning of the file
Ios :: app All output operation are performed at the end of
the file appending the content to the current
content of the file. This flag can only be used in
streams open for output – only operation
Ios :: trunk If the file opened for output operation already
exists then its previous contents are deleted and
replaced by the new one.
MODE OF OPENING A FILE
• All these flags can be combined using the bitwise operator OR | .
• For example if we want to open the file test.bin in binary mode to add data we could
do it by the following call to member function open().
• Ofstream myfile;
• Myfile.open(“test.bin”,ios::out | ios::app | ios :: binary);
MODE OF OPENING A FILE
• Each one of the open() member function of the classes of steram. Ifstream and fstream
has a default mode that is used if the file is opened without a second argument:
class Default mode parameter
ofstream Ios :: out
ifstream Ios ::in
fstream Ios ::in | ios::out
MODE OF OPENING A FILE
• For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively
assumed , even if a mode that does not include them is passed as second argument to the
open() member function.
• Let us see an example program that create a text file “example1.txt” and writes a line of text
in it:
• //opening a file and writing into it
• #include<iostream.h>
• #include<conio.h>
• #include<fstream.h>
• int main(){
• Ofstream myfile;
• myfile.open("example1.txt");
• myfile <<"this is a program that tells you how to write to a file."<<endl;
• myfile.close();
• getch();
• return 0;
• }
READING INPUT FILE
• #include<iostream.h>
• #include<fstream.h>
• #include<conio.h>
• Int main(){
• Ifstream myfile(“c:inputfile.txt”);
• Char ch[20];
• Int m;
• Myfile>>ch>>m;
• Cout<<ch<<“t”<<m;
• myfile.close();
• Getch();
• Return 0;
• }
CLOSE FILE
• Myfile.close();
OPENING FILES IN BINARY MODE
• To open a file in binary mode we need to set the file mode to ios::binary. Suppose we
have a binary file named as “test.dat” to open this file in binary mode we write the
statement as
• Ofstream myfile;
• Myfile.open(“test.dat”,ios::binary);
•
BOF() AND EOF()
• C++ provides special function bof() and eof() that are used to set the pointer to the
beginning of a file and at the end of a file respectively. The following sections explain
them with the help of proper examples.
• Bof() – beginning-of-file
• The bof() is a pointer which returns true if the current position of the pointer is at the
beginning of the input file stream and false otherwise. It means that it tells the
computer whether the cursor is at beginning of file or not.
BOF() AND EOF()
• Eof() –end-of-file
• The eof() is a pointer which returns true when there are no more data to be read from
an input file stream and false otherwise. It means that this function checks whether
controls has reached to the end of file or not. This function is very useful in the case
when we do not known the exact number of records in a file
BOF() AND EOF()
• Rules for using eof()
• Always test for the end-of-file condition before processing data
• Use a while loop for getting data from an input file stream, a for loop is desirable only
when you known the exact number of data items in the file
• // reading a text file using eof()
• #include<iostream.h>
• #include<conio.h>
• #include<fstream.h>
• Int main(){
• Char ch [50];
• Ifstream flag(“c://testrecord.txt”);
• Cout<<“output is”<<endl;
• While(flag.eof())
• {
• Flag>>ch;
• Cout<<ch<<endl;
• }
• Flag.close();
• Getch();
• Return 0;
• }
Output
All 20
Anwar 15
Zainab 17
Zonash 21
STREAM
• A stream can be thought of as a sequence of bytes of infinite length that is used as a
buffer to hold data to be processed. In C++ a stream is a sequence of bytes associated
with a file. Most of the times streams are used to assure a good and secure flow of
data between an application and file.
• In c++ there are two types of streams, input stream and output stream
• //consider the following example of input and output using the standard streams
• // input / output stream
STREAM
• #include<conio.h>
• #include<iostream.h>
• #include<process.h>
• Int main(){
• float height;
• Cout<<“enter your height”<<endl; //output stream
• Cin>> height; // input stream
• If(height <= 0)
• {
• Cout<<“yout entered an invalid height”<<endl;
• Exit(1);
• }
• Cout<<“your height is “<<height<<“feet”<<endl;
• Getch();
• Return 0;
• }
Output
Enter your height: 5.8
Your height is 5.8 feet
USE OF THE STREAM
• The data can be read from and written to files with the help of single character stream
and string stream
• Single character stream:
• Using single character stream the data can be read from and written to files character
by character.
• Reading files character by character :
• The function get() is used to read data character by character from files
• Consider the following program that reads the data one character at a time from the
file “character file.txt” display them on the screen
USE OF THE STREAM
• #include<conio.h>
• #include<iostream.h>
• #include<fstream.h>
• Int main(){
• Char ch;
• Ifstream reads(“c:characterfile.txt”);
• While (!reads.eof()){
• Read.get(ch);
• Cout<<ch<<endl;
• }
• Read.close();
• Getch();
• Return 0;
• }
Output
R
E
A
D
T
H
E
F
I
I
E
P
I
E
END OF C
++
WORK SMART
NOT
HARD

Mais conteúdo relacionado

Mais procurados

Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in JavaRavi_Kant_Sahu
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++NainaKhan28
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Chap4 oop class (php) part 1
Chap4 oop class (php) part 1Chap4 oop class (php) part 1
Chap4 oop class (php) part 1monikadeshmane
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in javaAtul Sehdev
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingSyed Faizan Hassan
 

Mais procurados (20)

Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
C++ classes
C++ classesC++ classes
C++ classes
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
Lecture 1 - Objects and classes
Lecture 1 - Objects and classesLecture 1 - Objects and classes
Lecture 1 - Objects and classes
 
Classes and objects in java
Classes and objects in javaClasses and objects in java
Classes and objects in java
 
Pj01 x-classes and objects
Pj01 x-classes and objectsPj01 x-classes and objects
Pj01 x-classes and objects
 
Class and object in c++
Class and object in c++Class and object in c++
Class and object in c++
 
C++ And Object in lecture3
C++  And Object in lecture3C++  And Object in lecture3
C++ And Object in lecture3
 
Ch03
Ch03Ch03
Ch03
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
4 Classes & Objects
4 Classes & Objects4 Classes & Objects
4 Classes & Objects
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Chap4 oop class (php) part 1
Chap4 oop class (php) part 1Chap4 oop class (php) part 1
Chap4 oop class (php) part 1
 
ITFT-Classes and object in java
ITFT-Classes and object in javaITFT-Classes and object in java
ITFT-Classes and object in java
 
Classes&amp;objects
Classes&amp;objectsClasses&amp;objects
Classes&amp;objects
 
How to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programmingHow to write you first class in c++ object oriented programming
How to write you first class in c++ object oriented programming
 
Oops in java
Oops in javaOops in java
Oops in java
 

Semelhante a Concept of Object-Oriented in C++

Semelhante a Concept of Object-Oriented in C++ (20)

C++ training
C++ training C++ training
C++ training
 
object oriented programing lecture 1
object oriented programing lecture 1object oriented programing lecture 1
object oriented programing lecture 1
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Introduction to c ++ part -1
Introduction to c ++   part -1Introduction to c ++   part -1
Introduction to c ++ part -1
 
oopm 2.pdf
oopm 2.pdfoopm 2.pdf
oopm 2.pdf
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
OOP Presentation.pptx
OOP Presentation.pptxOOP Presentation.pptx
OOP Presentation.pptx
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructors
 
Class and objects
Class and objectsClass and objects
Class and objects
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptx
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
C# by Zaheer Abbas Aghani
C# by Zaheer Abbas AghaniC# by Zaheer Abbas Aghani
C# by Zaheer Abbas Aghani
 
OOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and ObjectOOP Unit 2 - Classes and Object
OOP Unit 2 - Classes and Object
 
c++ lecture 1
c++ lecture 1c++ lecture 1
c++ lecture 1
 
c++ lecture 1
c++ lecture 1c++ lecture 1
c++ lecture 1
 
c++ introduction
c++ introductionc++ introduction
c++ introduction
 
Ooad ch 2
Ooad ch 2Ooad ch 2
Ooad ch 2
 
oop 3.pptx
oop 3.pptxoop 3.pptx
oop 3.pptx
 

Último

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 

Último (20)

Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 

Concept of Object-Oriented in C++

  • 1. OOP A U T H O R : A B D U L L A H J A N U N I T : 8
  • 2. OBJECT – ORIENTED PROGRAMMING • object-oriented programming (OOP) is a programming technique in which programs are written on the basis of objects. An object is a collection of data and function. Object may represent a person thing or place in real world. In OOP data and all possible functions on data are grouped together. Object oriented programs are easier to learn and modify. • Object – Oriented programming is a powerful technique to develop software. It is used to analyze and design the application in terms of objects. It deals with data and the procedure that process the data as a single object. • Some of the most object-oriented languages that have been developed • C++ • Java • Smalltalk • Eiffel • Clos
  • 3. FEATURE OF OBJECT ORIENTED PROGRAMMING • Objects : OOP provides the facility of programming based on objects. Objects is an entity that consists of data and functions. • Classes : classes are design for creating objects. OOP provides the facility to design classes for creating different objects. All properties and function of an object are specified in classes. • Real-world modeling: OOP is based on real-world modeling. As in real world things have properties and working capabilities similarly objects have data and function. Data represents properties and functions represent working of objects.
  • 4. FEATURE OF OBJECT ORIENTED PROGRAMMING • Reusability : OOP provides ways of reusing the data and code. Inheritance is a technique that allows a programmer to use the code of existing program to create new programs. • Information hiding: OOP allows the programmer to hide important data from the user. It is performed by encapsulation. • Polymorphism: polymorphism is an ability of an object to behave in multiple ways.
  • 5. OBJECTS • An object represents an entity in the real world such as a person, thing or concept etc. • An object is identified by its name. an object consists of the following two things: • Properties : properties are the characteristics of an object • Functions : function are the action that can be performed by an object. • Example : • Some example of objects of different types are as follows: Physical objects vehicles such as car, bus , truck etc; Electrical components
  • 6. OBJECTS Element of computer-user environment: windows menus graphics objects mouse and keyword User defined data types: time angles
  • 7. PROPERTIES OF OBJECT • The characteristics of an object are known as its properties' or attributes. Each object has its own properties. These properties can be used to describe the object. For example the properties of an object Person can be as follows: • Name • Age • Weight the properties of an object car can be as follow • Color • Price • Model • Engine power
  • 8. PROPERTIES OF OBJECT • The set of values of the of the attribute of a particular object is called its state. It means that the state of an object can be determined by the value of its attribute. The following figure shows the value of the attribute of an object Car.
  • 9. FUNCTIONAL OBJECT • An object can perform different tasks and actions. The actions that can be performed by an object are known as functions or methods. For example the object car can perform the following functions: • Start • Stop • Accelerate • Reverse The set of all function of an object represent the behavior of the object. It means that the overall behavior of an object can be determined the list of functions of that object.
  • 11. CLASSES • A collection of objects with same properties and functions is known as class. A class is used to define the characteristics of the objects. It is used as a model for creating different objects of same type. For example a class person can be used to define the characteristics and functions of a person. It can be used to create many objects of type. Person such as all, Usman , Abdullah etc. all objects of person class will have same characteristics and functions. However the values of each object can be different. The value are of the objects are assigned after creating an object. • Each object of a class is known as an instance of the class. For example, Ali, Usman and Abdullah are three instance of a class Person, similarly , mybook and your book can be two instance of a class Book
  • 12. CLASSES • Declaring a class • A class is declared in the same way as a structure is declared. The keyword class is used to declare a class. A class declaration specifies the variable and functions that are common to all objects of that class. The variable declared in a class are known as member variable or data members. The functions declared in a class are called member functions. • Syntax: • The syntax of declaring a class is as follows: • Class identifier • { • Body of the class • };
  • 13. CLASSES • Class :: it is the keyword that is used to declared a class • Identifier :: it is the name of the class. The rules for class name are same as the rules for declaring a variable. • The class declaration always ends with semi colon. All data members and members functions are declared within the braces known as body of the class. • Example : • Class test • { • Int n; • Char c; • Float x; • }; • The above class only contains data member in it. A class may contain both data members and member functions.
  • 14. ACCESS SPECIFIER The commands that are used to specify the access level of class members are known as access specifiers. Two most important access specifier are as follows
  • 15. THE PRIVATE ACCESS SPECIFIER • The private access specifier is used to restrict the use of class member within the class. Any member of the class declared with private access specifier can only be accessed within the class. It cannot be accessed from outside the class. It is also the default access specifier. • The data members are normally declared with private access specifier. It is because the data of an object is more sensitive. The private access specifier is used to protect data member from direct access from outside the class. These data member can only be used by the functions declared within the class.
  • 16. THE PUBLIC ACCESS SPECIFIER • The public access specifier is used to allow the user to access a class member within the class as well as outside the class. Any member of the class declared with public access specifier can be accessed from anywhere in the program • The member functions are normally declared with public access specifier. It is because the users access functions of an object from outside the class. The class cannot be used directly if both data member and member functions are declared as private.
  • 17. private: Int a; Char c; Float x; Public: Show(); Input(); test Outside the class
  • 18. • The above figure shows that data members a,c and x of class Test cannot be accessed from outside the class because they are declared with private access specifier. The member function show() and input() are accessible from outside the class because they are declared with public access specifier. The data members are accessed and manipulated indirectly though member functions.
  • 19. CREATING OBJECTS • An object is created in the same way as other variables are created. When an object of a class is created the space for all data member defined in the class is allocated in the memory according to their data types. An object is also known as instance. The process of creating an object of a class is also called instantiation • Syntax: • The syntax of creating an object of a class is as follow: • Class_name object_name; • Char_name it is the name of the class whose type of object is to be created • Object_name it is the name of the object to be created. The rules for object are same as the rules for declaring a variable.
  • 20. EXAMPLE • Test obj; • The above example declares an object obj of type test. The object contains all data members that are defined in class Test.
  • 21. EXECUTING MEMBER FUNCTION • An object of a particular class contains all data members as well as member functions defined in that class. The data member contains the value related to the object. The member functions are used to manipulate data members. The member functions can be executed only after creating an object. • Syntax: • The syntax of executing member functions is as follow • Object_name.function(); • Example : • Test obj; • Obj.input();
  • 22. • Write a program that declare a class with one integer data member and two member functions in() and out() to input and output data in data member. • #include<iostream> • Using namespace std; • Class test { • Private : • Int n; • Public : • Void in(){ • Cout<<“enter a number”; • Cin>>n; • } • Void out() • { • Cout<<“the value of n=“<<n; • }; • Void main(){ • Test obj; • Obj.in(); • Obj.out(); • Getch(); • }
  • 23. • Write a class marks with three data member to store three marks. Write three members functions in() to input marks, sum() to calculate and return the sum and avg() to calculate and return the average marks. • Class marks{ • Private: • Int a,b,c; • Public: • Void in(){ • Cout<<“enter three marks”; • Cin>>a>>b>>c; • } • Int sum(){ • Return (a+b+c)/3.0; • } • }; • Void main(){ • Mark m; • Int s; • Float a; • M.in(); • S = m.sum(); • A = m.avg(); • Cout<<“sum = “<<s<<endl; • Cout<<“average =“<<a; • Getch(); • Return 0;
  • 24. • Write a class circle with one data member radius. Write three member functions get_radius() to set radius value with parameter value area() to display radius and circum() to calculate and display circumference of circle. • Class circle{ • Private: • Float radius; • Public : • Void get_radius(float r) • { • Radius = r; • } • Void area() { • Cout<<“area of circle “<<3.14<<“radius”<<radius; • } • Void circum(){ • Cout<<“circumference of circle”<<2*3.14*radius*radius; • } • Void circum(){ • Cout<<“circumference of circle”<<2*3.14*radius; • } • };
  • 25. • Int main(){ • Circle c1; • Float rad; • Cout<<“enter radius”; • Cin>>rad; • C1.get_radius(rad); • C1.area(); • C1.cirum(); • Getch(); • }
  • 26. • Write a class book with three data member bookid , pages and price. It also contains the following member function: • The get() function is used to input values • The show() function is used to display values • The set() function is used to set the values of data members using parameters • The getprice() function is used to return the value of price. • The program should create two object of the class and input values for these objects • The program displays the detail of the most costly book. • Class book{ • Private: • Int bookid , pages ; • Float price; • Public : • Void get() • { • Cout<<“enter book id”; • Cin>>bookid;
  • 27. • Cout<<“enter pages”; • Cin>>pages; • Cout<<“enter price”; • Cin>>price; • } • Void show(){ • Cout<<“bookid”<<bookid<<endl; • Cout<<“pages=“<<pages<<endl; • Cout<<“price=“<<price<<endl; • } • Void set(int id, int pg, float pr) • { • Bookid = id; • Pages = pg; • Price = pr; • } • Int getprice() • { • Return price; • } • };
  • 28. • Int main(){ • Book b1, b2; • B1.get(); • B2.set(2,320,150,75); • Cout<<“ the detail of most costly book is as follow”<<endl; • If(b1.getprice() > b2.getprice()) • B1.show(); • Else • B2.show(); • Getch(); • }
  • 29. HOW ABOVE PROGRAM WORK • The above program create two objects of class Book. When two or more objects of the same class are created each object contains its own values in the memory. The data members of each object are separate to store the value of a particular object. However the members functions of the class are created only once in the memory. These member functions are shared by all objects of the class.
  • 31. • Write a class Result that contains roll no , name, and marks of three subjects. The marks are stored in an array of integers. The class also contains the following member functions. • The input() function is used to input the values in data members • The show() functions is used to displays the value of data members • The total() function returns the total marks of a student • The avg() function return the average marks of a student • The program should create an object of the class and call the member functions Class result{ Private : Int rno, marks[3]; Char name[50]; Public: Void input(){
  • 32. • Cout<<“enter roll no”; • Cin>>rno; • Cout<<“enter name”; • Gets(name); • For(int I = 0; i<3 ; i++) • { • Cout<<“enter marks[“<<i<<”]:”; • Cin>>marks[i]; • } • } • Void show(){ • Cout<<“roll no = ”<<rno<<endl; • Cout<<“name =“<<name<<endl; • For(int I = 0; i<3 ; i++) • Cout<<“marks [“<<i<<”]:”<<marks[i]<<endl; • }
  • 33. • Int total(){ • int t = 0; • For(int I = 0; i<3; i++) • t = t + marks[i]; • Return t; • } • Float avg(){ • Int t = 0; • For(int I = 0; i<3; i++) • T = t+marks[i]; • Return t/3.0; • } • }; • Void main(){ • Result r; • R.input(); • R.show(); • Cout<<“n total marks =“<<r.total()<<endl; • Cout<<“average marks = “<<r.avg()<<endl; • Getch(); • }
  • 34. DEFINING MEMBER FUNCTIONS OUTSIDE CLASS • The member function of a class can also be defined outside the class. The declaration of member functions is specified within the class and function definition is specified outside the class. The scope resolution operator :: is used in function declarator if the function is defined outside the class. • Syntax: • The syntax of defining member function outside the class is as follows: • Return_type class_name :: function_name(parameter) • { • Function body • }
  • 35. • Write a class array that contains an array of integers to store five values. It also contains the following member functions: • The fill() function is used to fill the array with values from the user. • The display() function is used to display the value of array. • The max() function shows the maximum values in the array. • The min() function shows the minimum value in the array. • All member function should be defined outside the class class array{ Private: Int a[5]; Public: Void fill(); Void display(); Int max(); Int min(); };
  • 36. • Void array :: fill(){ • For(int I = 0; i<5;i++) • { • Cout<<“enter a[“<<i<<”]; • Cin>>a; • } • } • Void array :: display() • { • For(int I = 0; i<5;i++) • Cout<<“a[“<<i<<”]:”<<a[i]<<endl; • } • Int array::max(){ • Int m = a[0]; • For(int I = 0; i<5;i++) • If(m < a[i]) • M = a[i]; • Return m; • }
  • 37. • Int array :: min(){ • Int m = a[0]; • For(int I = 0; i<5; i++) • If(m>a[i]) • M = a[i]; • Return m; • } • Void main(){ • Array arr; • Arr.fill(); • Cout<<“you entered the following values:”<<endl; • Arr.display(); • Cout<<“maximum value =“<<arr.max()<<endl; • Cout<<“maximum value = “<<arr.min(); • Getch(); • }
  • 38. CONSTRUCTOR • A type of member function that is automatically executed when an object of that class is created is known as constructor. The constructor has no return type and has same name that of class name. The constructor can work as a normal function but it cannot return any value. It is normally defined in classes to initialize data member • Syntax: • The syntax of declaring constructor is as follow: • Name(){ • Constructor • }
  • 39. • Write a class that displays a simple message on the screen whenever an object of that class is created • Class hello{ • Private: • Int n; • Public: • Hello(){ • Cout<<“object created …”<<endl; • } • }; • Void main(){ • Hello x,y,z; • Getch(); • }
  • 40. • Write a class that contains two integer data members which are initialized to 100 when an object is created. It has a member function avg that displays the average of data members. class number { Private: Int x,y; Public : Number(){ X = y = 100; } Void avg(){ Cout<<“x= “<<x<<endl; Cout<<“y=“<<y<<endl; Cout<<“average = “<<(x+y)/2<<endl; } }; Int main(){ Number n; n.avg(); Getch(); }
  • 41. USER DEFINED CONSTRUCTOR/EXPLICIT CONSTRUCTOR • When users define constructor in class for their own purpose. Especially for initialization of variables, then such type of constructor are called user defined constructors. • When constructor is declared for a class the compiler no longer provides an implicit default constructor. So the objects should be declared according to the constructor prototype that have been defined for the class. • Class Cexample { • Public: • Int a,b,c; • Cexample (int n, int m) • { • A = n; • B = m; • }
  • 42. • Int multiply(){ • C = a*b; • Return c; • } • }; • Int main(){ • Cexample Cobj(50,10); • Int result = Cobj.multiply(); • Cout<<“multiplication results is :”<<result; • Getch(); • Return 0; • } • Output :: • Multiplication result is : 5000
  • 43. PASSING PARAMETER TO CONSTRUCTOR • The method of passing parameter to a constructor is same as passing parameter to normal function. The only difference is that the parameter are passed to the constructor. When the object is declared. The parameter are written in parenthesis along with the object name in declaration statement. • Syntax: • The syntax of passing parameter to constructor is as follow: • Type object_name(parameters);
  • 44. • Example : • Class student{ • Private: • Int marks; • Char grade; • Public: • Student (int m, char g){ • Marks = m; • Grade = g; • } • Void show(){ • Cout<<“marks = “<<marks<<endl; • Cout<<“grade =“<<grade<<endl; • } • }; • Void main(){ • Student s1(730,’A’), s2(621,’B’); • Cout<<“record of student 1:”<<endl; • S1.show(); • Cout<<“record of student 2:”<<endl; • S2.show(); • Getch(); • Return 0; • }
  • 45. Write a class TV that contains attribute of Brand Name Model and Retail Price. Write a method to display all attribute and a method to change the attribute. Also write a constructor to initialize all the attribute. Class Tv { Public: Tv(char Brand[], char Mod[], float Price); Void change(char Brand[], char Mod[], float price); Void display(); Private: Char BrandName[20]; Char Model[10]; Float Retailprice; }; Tv :: Tv(char Brand[], char Mod[], float price) { Strcpy(BrandName,Brand); Strcpy(Model, Mod); RetailPrice = Price; }
  • 46. • Void Tv :: Change(Char Brand[], char Mod[], float Price) • { • Strcpy(BrandName, Brand); • Strcpy(Model, Mod); • RetailPrice = Price; • } • Void Tv :: Display() • { • Cout<<“Brand Name: ”<<BrandName<<endl; • Cout<<“Model:”<<Model<<endl; • Cout<<“Price:”<<RetailPrice<<endl; • } • Void main(){ • Tv Test(“Sony”, “HDTV”, “25000”); • Cout<<“Displaying the object …”<<endl; • test.display(); • Test.Change(“Toshiba”,”STDV”,220000); • Cout<<“displaying object after change…”<<endl; • Test.display(); • Getch(); • } Output Displaying the object…. Brand Name: Sony Model : HDTV Price : 25000 Displaying object after change…. Brand Name : Toshiba Model : SDTV Price : 22000
  • 47. CONSTRUCTOR OVERLOADING • The process of declaring multiple constructor with same name but different parameter is known as constructor overloading. The constructor with same name must differ in one of the following ways • Number parameter • Type of parameter • Sequence of parameter
  • 48. • Class over{ • Private: • Int num; • Char ch; • Public: • Over(){ • Num = 0; • Ch = ‘x’; • } • Over (int n , char c){ • Num = n; • Ch = c; • } • Void show(){ • Cout<<“num = “<<num<<endl; • Cout<<“ch =“<<ch<<endl; • } • }; • Int main(){
  • 49. • Over first, second(100,’p’); • Cout<<“the contents of first”<<endl; • First.show(); • Cout<<“the contents of second”<<endl; • Second.show(); • Getch(); • } Output The content of first : Num = 0 Ch = x The contents of second Num = 100 Ch = p
  • 50. DEFAULT COPY CONSTRUCTOR • A type of constructor that is used to initialize an object with another object of the same type is known as default copy constructor. Its name is “default copy constructor” because it is available by default in all classes. The user does not need to write this constructor. It accepts a single object of the same type as parameter. The parameter for default copy constructor can be given in parenthesis or using assignment operator. • Syntax: • Class_name object_name(parameter); OR • Class_name object_name = parameter;
  • 51. • Class Book{ • private: • Int pg,pr; • Char title[50]; • Public: • Void get(){ • Cout<<“enter title :”; • Gets(title); • Cout<<“enter pages :”; • Cin>>pg; • Cout<<“enter price :”; • Cin>>pr; • } • Void show(){ • Cout<<“title :”<<title<<endl; • Cout<<“pages :”<<pg<<endl; • Cout<<“Price :”<<pr<<endl; • } • };
  • 52. • Int main(){ • Book b1; • B1.get(); • Book b2(b1); • Book b3 = b1; • Cout<<“the detail of b1:”<<endl; • B1.show(); • Cout<<“the detail of b2 :”<<endl; • B2.show(); • Cout<<“the detail of b3 :”<<endl; • B3.show(); • Getch(); • Return 0; • } Ouput Enter title : visual programming Enter pages : 637 Enter price : 200 The detail of b1: Title : visual Programming Pages : 637 Price : 200 The detail of b2 : Title : visual programming Pages : 637 Price : 200 The detail of b3 Title : visual programming Pages : 637 Price : 200
  • 53. DESTRUCTOR • A type of member function that is automatically executed when an object of that class is destroy is known as destructor. The destructor has no return type and its name is same as class name. the constructor cannot return any value. It also cannot accept any parameters . The constructor name is preceded by tilde sign ~ , • syntax: • ~name(){ • Destructor body • }
  • 54. • Example : • Class test{ • Private: • Int n; • Public: • Test() • { • Cout<<“object created ….”<<endl; • } • ~test(){ • Cout<<“object destroyed ….”<<endl; • } • }; • Int main(){ • Test a, b; • Getch(); • } Output Object created … Object created … Object destroyed… Object destroyed ….
  • 55. FRIEND FUNCTION • A type of function that is allowed to access the private and protected member of a particular class from outside the class is called friend function. Normally the private and protected member of any class cannot be accessed from the outside the class. In some situations a program may require to access these member. The use of friends functions allow the user to access these members.
  • 56. • Example: • Class B; • Class A{ • Private : • Int a; • Public: • A() • { • A = 10; • } • Friend int show(A,B); • }; • Class B{ • Private : • Int b; • Public : • B(){ • B = 20; • } • Friend int show(A,B); • };
  • 57. • Int show(A x, B y){ • Int r; • R = x.a + y.b; • Cout<<“the value of class a object =“<<x.a<<endl; • Cout<<“the value of class b object”<<y.b<<endl; • Cout<<“the sum of both values =“<<endl; • } • Int main(){ • A obj1; • B obj2; • Show(obj1,obj2); • Getch(); • }
  • 58. FRIEND CLASS • A type of class all of whose member functions are allowed to access the private and protected members of a particular class is called friend class. • Example : • Class A{ • Private: • Int a,b; • Public: • A(){ • a= 10; • b= 20; • } • Friend class B; • };
  • 59. • Class B{ • Public: • Int showA(A obj){ • Cout<<“the value of a :”<<obj.a<<endl; • } • Int showB(A obj) • { • Cout<<“the value of b:”<<obj.b<<endl; • } • }; • Int main(){ • A x; • B y; • y.showA(x); • y.showB(x); • Getch(); • }
  • 60. INHERITANCE • A programming technique that is used to reuse an existing class to build a new class is known as inheritance. The new class inherits all the behavior of the original class. The existing class that is reused to create a new class is known as super class, base class or parent class. The new class that inherits the properties and functions of an existing class is known as subclass, derived class or child hierarchy. • Inheritance is one of the most powerful features of object oriented programming. The basic principle of inheritance is that each subclass shares common properties with the class from which it is derived.
  • 61. EXAMPLE • Suppose we have a class named vehicle. The subclass of this class may share similar properties such as wheels and motor etc. additionally a subclass may have its own particular characteristics for example a subclass Bus may have seats for people but another subclass Truck may have space to carry goods. vehicle Bus motorcycle truck
  • 62. ADVANTAGES Reusability : • Inheritance allows the developer to reuse existing code in many situations. A class be created once and it can be reused again and again to create many sub classes. Save time and effort : • Inheritance saves a lot of time and effort to write the same classes again. The reusability of existing classes allows the program to work only on new classes. Increase program structure and reliability : • A super class is already compiled and testing properly. This class can be used in a application without compiling it again. The use of existing class increase program reliability.
  • 63. CATEGORIES OF INHERITANCE • Single inheritance : • A type of inheritance in which a child class is derived from the single parent class is known as single inheritance. The child class in this inheritance inherits all data members and member functions of the parent class. It can also add further of its own. parent child
  • 64. MULTIPLE INHERITANCE • A type of inheritance in which a child class is derived from multiple parent classes is known as multiple inheritance. The child class in this inheritance inherits all data members and member function of all parent classes. It can also add further capabilities of its own. Parent 1 child Parent 2
  • 65. PROTECTED ACCESS SPECIFIER • It allow a protected data member to be accessed from all derived classes but not from anywhere else in the program. It means that child class can access all protected data member of its parent class.
  • 66. SPECIFYING A DERIVED CLASS • The process of specifying derived class is same as specifying simple class. Additionally the reference of parent is specified along with derived class name to inherit the capabilities of parent class. • Syntax: • The syntax of specifying a derived class is as follow • Class sub_class : specifier parent_class • { • Body of the class • }; • Class it is the keyword that is used to declared a class • Sub_class it is name of derived class • : it create a relationship b/w derived class and super class • Specifier it indicates the type of inheritance. It can be private , public or protected. • Parent_class it indicate the name of parent class that is being inherit
  • 67. • Example : • Class move{ • Protected: • Int position; • Public: • Move(){ • Position = 0; • } • Void forward(){ • Position++; • } • Void show(){ • Cout<<“Position =“<<position<<endl; • } • };
  • 68. • Class move2 : public move { • Public : • Void backward(){ • Position--; • } • }; • Int main(){ • Move2 m; • M.show(); • M.forward(); • M.show(); • M.backward(); • M.show(); • Getch(); • }
  • 69. POLYMORPHISM • Polymorphism is the ability to use an operator or function in multiple ways. Polymorphism gives different meaning or functionality to the operator or functions. Poly refer to many , signifies(meaning) that there are many uses of these operator and functions. • In C++ polymorphism can be achieved by one of the following concepts. • Function overloading • Operator overloading • Virtual function
  • 70. POLYMORPHISM • The word polymorphism is a combination of two words poly and morphism. Poly means many and morphism means form. In object-oriented programming polymorphism is the ability of objects of different types to respond to function of the same name. the user does not have to known the exact type of the object in advance. The behavior of the object can be implemented at run time. It is called late binding or dynamic binding . Polymorphism is implemented by using virtual functions. • Pointer to objects: • A pointer can also refer to an object of a class. The member of an object can be accessed through pointers by using the symbol ->. The symbol is known as member access operator.
  • 71. POLYMORPHISM • Syntax: • Ptr -> member • Ptr it is the name of the pointer that reference an object • -> it is the member access operator that is used to access a member of object. • Member it is name of the class member to be accessed.
  • 72. • Example: • Class test{ • Private : • Int n; • Public : • Void in(){ • Cout<<“enter number”; • Cin>>n; • } • Void out(){ • Cout<<“the value of n = “’<<n; • } • }; • Int main(){ • Test *ptr; • Ptr = new test; • Ptr -> in(); • Ptr -> out(); • getch();
  • 73. • How above example work? • The above program declare a class test and a pointer ptr of type test. The pointer can refer to an object of the class. The new operator creates an object in the memory and stores the address in ptr. The program then uses the pointer to call the member functions of the object being referenced by the pointer. The symbol -> is used to access the member of any object through pointer. The user of dot operator with pointer to access any member is invalid.
  • 74. • Write a class that contains an attribute name, a function to input and a function to display name. creates array of pointer in which each element refers to an object of the class. • Class person • { • Private: • Char name[50]; • Public: • Void get(){ • Cout<<“enter your name”; • Cin>>name; • } • Void show(){ • Cout<<“your name =“<<name<<endl; • } • }; • Int main(){ • Person *ptr[5]; • Int I; • For(I = 0; i<5; i++){ • Ptr[i] =new person; • Ptr[i] ->get(); • } • For(i=0; i<5; i++) • Ptr[i] -> show(); • Getch(); • }
  • 75. OPERATOR OVERLOADING • The process of defining additional meanings of operators is known as operator overloading. It enables an operator to perform different operations depending on the type of operands. It also enables the operators to process the user-defined data types. • The basic arithmetic operators such as +,-,* and / normally work with basic types such as int , float and long etc.
  • 76. OVERLOADING AN OPERATOR • An operator can be overloaded by declaring a special member function in the class. The member function uses the keyword operator with the symbol of operator to be overloaded. • Syntax: • The syntax of overloading an operator is as follow • Return_type operator op() • { • Function body • } • Example : • Void operator ++() • { • Function body; • }
  • 77. OVERLOADING ++ OPERATOR • The increment operator ++ is a unary operator. It works with single operand. It increase the value of operand by 1. it only works with numerical values by default. It can be overloaded to enable it to increase the values of data members of an object in the same way. • Program : • Write a program that overload increment operator to work with user-defined objects.
  • 78. • Class count • { • Private: • Int n; • Public: • Count(){ • N = 0; • } • Int show(){ • Cout<<“n=“<<n<<endl; • } • Int operator ++(){ • N = n+1; • } • }; • Int main(){ • Count obj; • Obj.show(); • ++obj; • Obj.show(); • Getch(); • Return 0;
  • 79. VIRTUAL FUNCTION • Virtual means existing in effects but not in reality. A type of function that appears to exist in some part of a program but does not exist really is called virtual function. Virtual function are used to implement polymorphism. They enable the user to execute completely different function by the same function call. • A virtual function is defined in the parent class and can be overridden in child classes. It is defined by using the keyword virtual.
  • 80. VIRTUAL FUNCTION • A virtual function is a special type of member function. It is defined in the base class and may be redefined in any class derived from this base class. Its name in the base class and in the derived classes remain the same. Its definition in these classes may be different. • The virtual function in derived class is executed through the pointer of the public base class. • A virtual function is declared by writing the word virtual before function declaration in the base class. The function with the same name are declared in the derived classes.
  • 81. • Example: • Class a{ • Public: • Virtual void show(){ • Cout<<“parent class a…”<<endl; • } • }; • Class b : public a{ • Public: • Void show(){ • Cout<<“child class b…..”<<endl; • } • }; • Class c : public a { • Public: • Void show() • { • Cout<<“child class c…”<<endl; • } • };
  • 82. • Int main(){ • A obj1; • B obj2; • C obj3; • A *ptr; • Ptr = &obj1; • Ptr->show(); • Ptr = &obj2; • Ptr -> show(); • Ptr = &obj3; • Ptr->show(); • Getch(); • } Ouput Parent class A…… Child class b…… Child class C….
  • 83. FILE HANDLING A U T H O R : : A B D U L L A H J A N
  • 84. INTRODUCTION • A file is a collection of related records that are permanently stored in secondary storage. • File handling is an important feature of C++ language. This unit describe different types of files such as text files and binary files and describe how different operation like opening reading writing and closing are performed on files.
  • 85. FILE HANDLING • The combination of character words and record are called files. Suppose we have a file on the disk and want to open it then reading from or writing into the file before closing it will be termed as handling files. The basic steps involved in the file handling are : • Opening file • Reading and writing a file • Closing file
  • 86. TYPES OF FILE • Text files: are those files that store data in text format which is readable by humans example of text file is the c++ source program which can be read by human. • Binary files: store data in binary format which is not readable by humans but readable by computers. Binary files are directly processed by computer. Binary files are normally used to store large data files. They take less space to store data as compared to text files. Forexample an integer having length of six digits will take six bytes to accommodate in a text file while in binary files they only two bytes, the best example of binary file is the object of a c++ source file that is generated by the computer of c++.
  • 87. OPENING FILE • To open a file the function open() is used whose syntax is: • Myfile.open(filename); • Here myfile is an internal variable actually an object used to handle the file whose name is written in the parenthesis. To declare this variable the following statement is used : • Ifstream myfile ;
  • 88. MODE OF OPENING A FILE • While opening a file we tell the compiler what we want to do with it i.e we want to read the file or write into the file or want to modify it. In order to open a file in any desired mode the member function open() should take mode as an argument along with the file name. • Its general syntax is below: • Open (filename, mode); • Here file name representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags.
  • 89. MODE OF OPENING A FILE Ios :: in open for input operation Ios :: out Open for output operation Ios :: binary Open in binary mode Ios :: ate Set the initial position at the end of the file. If this flags is not set to any value the initial position is the beginning of the file Ios :: app All output operation are performed at the end of the file appending the content to the current content of the file. This flag can only be used in streams open for output – only operation Ios :: trunk If the file opened for output operation already exists then its previous contents are deleted and replaced by the new one.
  • 90. MODE OF OPENING A FILE • All these flags can be combined using the bitwise operator OR | . • For example if we want to open the file test.bin in binary mode to add data we could do it by the following call to member function open(). • Ofstream myfile; • Myfile.open(“test.bin”,ios::out | ios::app | ios :: binary);
  • 91. MODE OF OPENING A FILE • Each one of the open() member function of the classes of steram. Ifstream and fstream has a default mode that is used if the file is opened without a second argument: class Default mode parameter ofstream Ios :: out ifstream Ios ::in fstream Ios ::in | ios::out
  • 92. MODE OF OPENING A FILE • For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed , even if a mode that does not include them is passed as second argument to the open() member function. • Let us see an example program that create a text file “example1.txt” and writes a line of text in it: • //opening a file and writing into it • #include<iostream.h> • #include<conio.h> • #include<fstream.h> • int main(){ • Ofstream myfile; • myfile.open("example1.txt"); • myfile <<"this is a program that tells you how to write to a file."<<endl; • myfile.close(); • getch(); • return 0; • }
  • 93. READING INPUT FILE • #include<iostream.h> • #include<fstream.h> • #include<conio.h> • Int main(){ • Ifstream myfile(“c:inputfile.txt”); • Char ch[20]; • Int m; • Myfile>>ch>>m; • Cout<<ch<<“t”<<m; • myfile.close(); • Getch(); • Return 0; • }
  • 95. OPENING FILES IN BINARY MODE • To open a file in binary mode we need to set the file mode to ios::binary. Suppose we have a binary file named as “test.dat” to open this file in binary mode we write the statement as • Ofstream myfile; • Myfile.open(“test.dat”,ios::binary); •
  • 96. BOF() AND EOF() • C++ provides special function bof() and eof() that are used to set the pointer to the beginning of a file and at the end of a file respectively. The following sections explain them with the help of proper examples. • Bof() – beginning-of-file • The bof() is a pointer which returns true if the current position of the pointer is at the beginning of the input file stream and false otherwise. It means that it tells the computer whether the cursor is at beginning of file or not.
  • 97. BOF() AND EOF() • Eof() –end-of-file • The eof() is a pointer which returns true when there are no more data to be read from an input file stream and false otherwise. It means that this function checks whether controls has reached to the end of file or not. This function is very useful in the case when we do not known the exact number of records in a file
  • 98. BOF() AND EOF() • Rules for using eof() • Always test for the end-of-file condition before processing data • Use a while loop for getting data from an input file stream, a for loop is desirable only when you known the exact number of data items in the file • // reading a text file using eof() • #include<iostream.h> • #include<conio.h> • #include<fstream.h>
  • 99. • Int main(){ • Char ch [50]; • Ifstream flag(“c://testrecord.txt”); • Cout<<“output is”<<endl; • While(flag.eof()) • { • Flag>>ch; • Cout<<ch<<endl; • } • Flag.close(); • Getch(); • Return 0; • } Output All 20 Anwar 15 Zainab 17 Zonash 21
  • 100. STREAM • A stream can be thought of as a sequence of bytes of infinite length that is used as a buffer to hold data to be processed. In C++ a stream is a sequence of bytes associated with a file. Most of the times streams are used to assure a good and secure flow of data between an application and file. • In c++ there are two types of streams, input stream and output stream • //consider the following example of input and output using the standard streams • // input / output stream
  • 101. STREAM • #include<conio.h> • #include<iostream.h> • #include<process.h> • Int main(){ • float height; • Cout<<“enter your height”<<endl; //output stream • Cin>> height; // input stream • If(height <= 0) • { • Cout<<“yout entered an invalid height”<<endl; • Exit(1); • } • Cout<<“your height is “<<height<<“feet”<<endl; • Getch(); • Return 0; • } Output Enter your height: 5.8 Your height is 5.8 feet
  • 102. USE OF THE STREAM • The data can be read from and written to files with the help of single character stream and string stream • Single character stream: • Using single character stream the data can be read from and written to files character by character. • Reading files character by character : • The function get() is used to read data character by character from files • Consider the following program that reads the data one character at a time from the file “character file.txt” display them on the screen
  • 103. USE OF THE STREAM • #include<conio.h> • #include<iostream.h> • #include<fstream.h> • Int main(){ • Char ch; • Ifstream reads(“c:characterfile.txt”); • While (!reads.eof()){ • Read.get(ch); • Cout<<ch<<endl; • } • Read.close(); • Getch(); • Return 0; • } Output R E A D T H E F I I E P I E
  • 104. END OF C ++ WORK SMART NOT HARD