Professional Documents
Culture Documents
OOP. Complete PDF
OOP. Complete PDF
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
What is Constructor?
• A constructor is a special member function of a
class that is executed whenever we create new
objects of that class.
• Constructor is automatically called when the object is
created. Constructors are not usually called explicitly
by us.
• Constructor is used to initialize the objects of a
class.
• Constructor Properties
− Constructor is a special function having same name as the
class name
− Constructor does not have return type
− Constructors are commonly public members
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
What would happen if we called the member function
area( ) before having called set values(int a,int b)???
return width*height;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• An undetermined result since the member
height and width have never been assigned
a value.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example:
• #include <iostream>
• #include<conio.h>
• using namespace std;
• class test
• {
• public:
• test( )
• {
• cout<<"welcome"<<endl;
• }
• };
• int main(int argc, char** argv) {
• test a,b,c;
• getch();
• return 0;
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example:
• #include <iostream>
• #include<conio.h> int main( ) {
• using namespace std; myclass ob; // automatic call to
constructor
• class myclass { ob.show( );
• int a;
return 0;
}
• public:
• myclass( ); //constructor
• void show( );
• };
• myclass::myclass( )
• {
• a=10;
• }
• void myclass::show( )
• {
• cout << a;
• } C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example
#include<iostream> void main()
#include<conio.h> {
usingnamespace std;
rectangle rect ,rectb;
class rectangle
{ cout<<"area="<<rect.area()<<endl;
private:
int width, height;
public: cout<<"area="<<rectb.area();
rectangle( );
int area(); getch();
};
rectangle::rectangle( ) }
{
width=3;
height=4;
}
int rectangle:: area()
{
return width*height;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Practice Question:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1202)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Types of Constructor
• Parameterized constructor
• class constructor
{
constructor( )
{
// body of constructor
}
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
2. Parameterized Constructor:
• The method of passing parameter to a constructor is
same as passing parameter to normal function.
• class constructor
{
constructor(parameters )
{
// body of constructor
}
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example:
#include<iostream> int _tmain(int argc, _TCHAR* argv[])
#include<conio.h> {
usingnamespace std;
circle cir(9);
class circle
{
private: .
cout<<"circumference = \t"<<cir circum();
int radius;
public: getch();
circle(int r) return 0;
{ }
radius=r;
}
int circum()
{
return 2*3.14*radius;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Example
#include<iostream> int main()
#include<conio.h> {
usingnamespace std;
int x,y;
class rectangle
{ cin>>x>>y;
private:
int width, height; rectangle rect(x,y);
public:
rectangle(int a, int b) cout<<rect.area();
{
return 0;
width=a;
height=b; }
}
int area()
{
return width*height;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Practice Question
• Define a class HOTEL in C++ with the following description:
• Private Members
• · RNo //Data Member to store Room No
• · Name //Data Member to store customer Name
• · Tariff //Data Member to store per day charge
• · NOD //Data Member to store Number of days
• Public Members:
• · A parameterized constructor function to initialize data members
• · CALC( ) //A function to calculate and return amount as NOD*Tariff
• · Checkout( ) //A function to display Rno, Name, Tariff, NOD and Amount
(Amount to be displayed by calling function CALC( )
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1202)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Copy Constructor
• A copy constructor is a special constructor for
creating a new object as a copy of an existing object.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Default Copy Constructor
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example:
• #include <iostream>
int main(int argc, char** argv) {
• #include<conio.h>
Marks obj(10,20);
• using namespace std;
• class Marks
Marks obj2=obj; //copy constructor
• {
• private:
obj.display();
• int maths, science;
• public:
• Marks(int m, int s)
obj2.display();
• {
• maths=m; return 0;
• science=s; }
}
• void display()
• {
• cout<<"Maths="<<maths<<endl;
• cout<<"Science="<<science<<endl;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1202)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Passing Parameters to Functions:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Passing Parameters by Value
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example
For example. in the below code, value of x is modified
using the function fun().
#include <iostream>
using namespace std;
void fun(int x) {
x = 30;
} Output:
x = 20
int main() {
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Pass by Reference
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
#include <iostream>
#include<conio.h>
using namespace std;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example:
• class Marks
• { int main(int argc, char** argv) {
• private:
• int maths, science; Marks obj(10,20);
• public:
• Marks(int m, int s) Marks obj2(obj).; //copy constructor
• {
• maths=m;
• science=s;
obj.display();
}
obj2.display();
• Marks(const Marks & o)
• {
• maths=o.maths;
return 0;
• science=o.science }
• }
• void display()
• {
• cout<<"Maths="<<maths<<endl;
• cout<<"Science="<<science<<endl;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
• All member values of one object can be
assigned to other object using copy
constructor.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
OBJECT ORIENTED PROGRAMMING(CS-1202)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Function Overloading
• The process of declaring multiple functions with same
name but different parameters is called function
overloading.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• The user can use same name and pass
different types of parameters.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Output
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Constructor overloading
• In C++, We can have more than one constructor in a class with
same name, as long as each has a different list of arguments.
• This concept is known as Constructor Overloading and is quite
similar to function overloading.
• Overloaded constructors essentially have the same name .The
constructors with same name must differ in one of the following
ways.
• Number of parameters
• Type of parameter
• Sequence of parameters
• A constructor is called depending upon the number and type of
arguments passed.
• While creating the object, arguments must be passed to let
compiler know, which constructor needs to be called.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 12
Example
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 13
Example
#include<conio.h>
#include<iostream>
Using namespace std;
class sum
{
public:
sum(int l,int m, int n)
{
cout<<"sum of 3 integers is
="<<(l+m+n)<<endl;
}
sum(int l,int m)
{
cout<<"sum of 2 integers is
="<<(l+m)<<endl;
}
};
int main()
{
sum x(6,2),y(7,6,9);
return 0;
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 14
Example:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 15
Practice Questions:
• Write three versions of a function “line”. The first version takes no
parameter and displays a line of 10 asterisks. The second version takes an
integer parameter and displays a line of n asterisks. The third version
takes an integer and a character as parameters and displays a line of given
character of n length.
• Create a class named 'Rectangle' with two data members- length and
breadth and a function to calculate the area which is 'length*breadth'. The
class has three constructors which are :
1 - having no parameter - values of both length and breadth are assigned
zero.
2 - having two numbers as parameters - the two numbers are assigned as
length and breadth respectively.
3 - having one number as parameter - both length and breadth are
assigned that number.
Now, create objects of the 'Rectangle' class having none, one and two
parameters and print their areas.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 16
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Lifetime of Object
• Lifetime is defined as time between creation and
destruction of object.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
#include<iostream.h>
#include<conio.h> int main()
class student {
{
private: student st; //local object
int rn;
float fees;
st.readdata();
public: st.writedata();
void readdata() getch();
{ return 0;;
cout<<"Enter the rollno. and fees of the student"; }
cin>>rn>>fees;
}
void writedata()
{
cout<<"The rollno. is "<<rn<<endl;
cout<<"The fees is "<<fees<<endl;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
2.External/ Global Objects
• External objects are persistent throughout the lifetime
of a program and having file scope.
• Their visibility is throughout the module source file.
• Declaration: An external object is declared outside
the scope of any braces.
• rectangle rect; //outside main function exist globally
• {
• // statements;
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
• The main reason of external objects would be to
make the object visible in other source files which are
in the same system.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Header File
• #include<iostream>
• using namespace std;
• class a
• {
• int marks;
• public:
• a()
• {
• marks=11;
•
• }
• void ut()
• {
• cout<<marks;
• }
• };
• a obj;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
#include"a.h" int main(){
#include<conio.h>
#include<iostream> for(int i=0;i<=2;i++)
using namespace std; { bb o;
class bb static bb o2;
{ cout<<"local object value";
int mar; o.get(5);
int n; o.show();
public: cout<<"static object value";
bb() o2.get(10);
o2.show();
{ cout<<"global object value";
n=0; go.get(7);
go.show();
} }
void get(int x)
{ cout<<"External object value"<<endl;
n=x+n; obj.ut();
}
void show( ) getch();
{ return 0;
cout<<endl<<n<<endl; }
}
};
bb go;
12
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 13
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Pointers:
• The variables that are used to hold the memory address of
another variable is called a pointer variable
• The data type of the variable (whose address a pointer is to
hold) and the pointer variable must be same.
• Declaration Syntax:
• A pointer variable is declared by placing an asterisk(*) after data
type or before the variable name in declaration statement.
• Datatype * variable name;
• E.g. if a pointer variable “P” is to hold the memory address of an
integer variable it is declared as:
• int *P
• Similarly if a pointer variable is to hold memory address of a
floating point variable, it is declared as
• float *a;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Pointer Operators:
• “*” and “&” are two special pointer operators.
• The “&” is unary operator that returns the memory address of its
operand.
• The second pointer operator “*” is the complement of &. It is the
unary operator that returns the value located at the address that
follows.
• E.g.
• int *x; // Pointer Declaration
• int a,b;
• a=10;
• x=&a; // Places address of “a” in x
• b=*x; // Places value at that address in b
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Dynamic Memory
• Suppose you want to put a toy in a box, but you only have an approximate
idea of its size. For that, you would require a box whose size is equal to
the approximate size of the toy.
• Now, while declaring the character array, if we specify its size smaller than
the size of the input string, then we will get an error because the space in
the memory allocated to the array is lesser than the size of the input
string. This is the same case as trying to fit a big toy in a smaller box. If we
specify its size much larger than the size of the input string, then the array
will be allocated a space in the memory which is much larger than the size
of the input string, thus unnecessarily consuming more memory even
when it is not required. This is like putting a small toy in a large box.
• In the above case, we don't have the idea about the size of the array until
the string is input by the user.
4
Dynamic Objects:
• Dynamic objects are used when the object to be
created is not predictable enough.
• This is usually when we cannot determine at compile
time
• Object identities
• Object qualities
• Object lifetimes
• Dynamic objects use dynamic memory allocation
• Dynamic objects can be created and destroyed at run
time
• In C++ a pointer can be directed to an area of
dynamically allocate memory at run time
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
The new operator
• The dynamically created objects are just like any
other object.
• When it is created its constructor is called.
• We can allocate and de allocate objects dynamically
using “new” and “delete” operators respectively.
• new
• The new operator is used to allocate memory at
runtime.
• Syntax: Classname *fp = new Classname;
• If you write A * a = new A() the default constructor of
the class A is called and it dynamically allocates
memory for one object of the class A and the address
of the memory allocated is assigned to the pointer a. 6
The delete Operator
• The delete operator is used to deallocate the memory
created by new operator at runtime. Once the
memory is no longer needed it should be free so that
the memory becomes available again for other
request of dynamic memory.
• Syntax:
• delete pointer-variable;
• In the delete operator the pointer-variable is the
pointer that points to the data object created by the
new.
• delete fp;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Destructor:
• ~class_name()
• {
• //Some code
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Passing Object as an Argument
• Object can also be passed as argument to member
functions.
• When an object is passed as argument to a member
function only the name of the object is written in the
argument list.
• The number of parameters and their types must be
defined in the member function to which the object is
to be passed.
• The objects that are passed are treated local for the
member functions and are destroyed when the
control returns to the calling function.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example:
• #include <iostream>
• using namespace std;
•
• class Example {
• public:
• int a;
•
• // This function will take
• // an object as an argument
• void add(Example E)
• {
• a = a + E.a;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Output:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example 2:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Output:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Returning Object From a Member
Function
• The method of returning an object from member function is
same as returning a variable
• If a member function returns an object its return type should bee
same as the type of object to be returned.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example:
• #include <iostream>
• using namespace std;
•
• class Example {
• public:
• int a;
•
• // This function will take
• // object as arguments and
• // return object
• Example add(Example Ea, Example Eb)
• {
• Example Ec;
• Ec.a = Ea.a + Eb.a;
•
• // returning the object
• return Ec;
• }
• };
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
Practice Question:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Friend Function
• A friend function can access members of class in
which it is declared.
• A friend function of a class is defined outside that
class' scope but it has the right to access all private
and protected members of the class.
• Even though the prototypes for friend functions
appear in the class definition, friends are not member
functions.
• A friend can be a function or member function, or a
class in which case the entire class and all of its
members are friends.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Syntax to Declare Friend Function
• To declare a function as a friend of a class, precede
the function prototype in the class definition with
keyword friend.
• class className
• { ……
• friend returnType functionName(arg list);
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Some Points to Remember
• There are some points to remember while implementing
friend functions in our program:
• A friend function can be declared in the private or public section
of the class.
• It can be called like a normal function without using the object.
• A friend function is not in the scope of the class, of which it is a
friend.
• A friend function is not invoked using the class object as it is not
in the scope of the class.
• A friend function cannot access the private and protected data
members of the class directly. It needs to make use of a class
object and then access the members using the dot operator.
• A friend function can be a global function or a member of
another class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example 1
• #include<conio.h>
• #include<iostream>
• Using namespace std;
class a
• {
• private:
• int i,j;
• public:
• void setvalues(int x,int y)
• {
• i=x;
• j=y;
• }
• friend void sum(a);
• };
• void sum(a o)
• {
• cout<< “sum = ” <<o.i+o.j;
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example 2:. Write a program to implement
“Friend Function” for different classes.
#include<iostream> class b
usingnamespace std; { int sum(a o,b o1)
private: {
class b; int j; return o.i+o1.j;
class a public: }
{ void setvalues(int y)
private: { void main()
int i; j=y; {
public: } a obj;
void setvalues(int x) friend int sum(a,b); b obj1;
{ }; obj.setvalues(7);
i=x; obj1.setvalues(8);
} cout<<"sum = "<<sum(obj,obj1);
friend int sum(a,b); getch();
}; }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Practice Question:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Operator Overloading
• The process of defining additional meanings of
operators is known as operator overloading.
• It enables an operator to perform operations depending
on the type of operands.
• It also enables the operators to process user defined
data types.
• The basic arithmetic operators such as +,-,* and /
normally work with basic data types such as int, float
and long etc.
• The application of these operators with basic data types
are already defined in the language.
• However an error will occur if these operators are used
with user defined data types.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example
• The addition operator is used to add two numeric values.
Suppose a, b and c are three integer variables. The
following statement will add the contents of a and b and
store the result in variable c.
• c=a+b;
• Example:
• void operator++( )
• {
Function body;
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Overloading Unary Operators
• A type of operator that works with single
operand is called unary operator.
• + , - , *, ++, -- etc.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Overloading ++ Operator
• The increment operator ++ is a unary operator. It
works with single operand. It increases the value
of operand by 1.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Example Program:
class count int main( )
{ {
private: count obj;
int n,m; cout<<"Values before increment"<<endl;
public: obj.show( );
count( )
{ ++obj;
n=0; cout<<"Values after increment"<<endl;
m=1; obj.show();
} getch( );
void operator++( ) return 0;
{ }
n=n+1;
m=m+1;
}
void show( )
{
cout<<"n ="<<n<<endl;
cout<<"m ="<<m<<endl;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Overloading Postfix Increment
Operator
class count int main( )
{ {
private: count obj;
int n,m; cout<<"Values before increment"<<endl;
public: obj.show( );
count( )
{ obj++;
n=0;
m=1; cout<<"Values after increment"<<endl;
} obj.show();
void show( ) getch( );
{ return 0;
cout<<"n ="<<n<<endl; The keyword }
cout<<"m ="<<m<<endl;
} “int” in
void operator++( int) following
{ statement
n=n+1;
indicates that
m=m+1; operator is
`} overloaded
}; for postfix
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
Practical Question:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 10
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Composition
• In real-life, complex objects are often built from smaller, simpler
objects. For example, a car is built using a metal frame, an engine,
some tires, a transmission, a steering wheel, and a large number of
other parts.
• A personal computer is built from a CPU, a motherboard, some
memory, etc…
• Even you are built from smaller parts: you have a head, a body, some
legs, arms, and so on. This process of building complex objects from
simpler ones is called object composition
• . Broadly speaking, object composition models a “has-a” relationship
between two objects.
• A car “has-a” transmission. Your computer “has-a” CPU. You “have-a”
heart.
• The complex object is sometimes called the whole, or the parent. The
simpler object is often called the part, child, or component.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Composition Continued…
• In a composition relationship, the object of whole is responsible for the
existence of the parts. Most often, this means the part is created when
the object is created, and destroyed when the object is destroyed.
• But more broadly, it means the object manages the part’s lifetime in
such a way that the user of the object does not need to get involved.
For example, when a body is created, the heart is created too. When a
person’s body is destroyed, their heart is destroyed too. Because of
this, composition is sometimes called a “death relationship”.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Composition Continued…
• You simply create objects of your existing class inside the new
class. This is called composition because the new class is
composed of objects of existing classes.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Example
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example Program:
#include "stdafx.h" class B class C
#include <iostream> { {
#include<conio.h> int d,e;
public: A o;
using namespace std; int c; B ob;
class A B() public:
{ { C( )
int a,b; c=5; {
public: } d=6;
A() void sho() e=7;
{ { }
a=2; cout<<endl<<c<<endl; void dis()
b=3; } {
} };
void show() cout<<"Data members of A = ";
{ o.show();
cout<<endl<<a<<"\n"<<b<< cout<<"Data members of B = ";
"\n"; ob.sho();
} cout<<"Data members of C = ";
}; cout<<endl<<d<<"\n"<<e;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Output:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example Program
#include "stdafx.h" class B class C
#include <iostream> { {
#include<conio.h> int d,e;
public: A o;
using namespace std; int c; B ob;
class A B(int z) public:
{ { C(int t,int y,int q,int w,int
int a,b; c=z; s):o(q,w),ob(s)
public: } {
A(int x,int y) void sho() d=t;e=y;
{ { }
a=x;b=y; cout<<c<<"\n"; void dis()
} } {
void show() }; cout<<ob.c;
{ o.show();
cout<<a<<"\n"<<b<<"\n"; ob.sho();
} cout<<d<<"\n"<<e;
}; }
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Inheritance
• Inheritance is an important feature of the object
oriented programming.
• Base Class:
The existing class that is inherited is
called base class or parent class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Example
• we have a class Shape which is a base class for two class class
Rectangle and class Triangle. In inheritance, derived classes derived
from base class acquire all the features of the base class with its own
other features.
• According these details lets see a pictorial example of Inheritance in
C++ :-
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Single Inheritance:
• In single inheritance the new class is derived
from only one base class.
• Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
Protected Members:
• Public Inheritance
• Protected Inheritance
• Private Inheritance
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Public Inheritance:
• If base class is inherited as public, then the
base class protected members become the
protected members of derived class and
public members of base class become the
public members of derived class.
• Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8
Example Program1:
#include<conio.h> class Rectangle: public Shape Output:
#include<iostream> {
usingnamespace std; public:
int getArea()
{
// Base class return (width * height);
class Shape }
{ };
protected:
int width; int main( )
int height; {
Rectangle Rect;
public: Rect.setWidth(5);
void setWidth(int w) Rect.setHeight(7);
{
width = w; // Print the area of the object.
} cout << "Total area: " <<
void setHeight(int h) Rect.getArea() << endl;
{ return 0;
height = h; }
}
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 9
};
Example Program2:
#include<conio.h> class derived1: public base int main( )
#include<iostream> { {
usingnamespace std; // i & j are inherited as protected derived1 obj1;
int k; derived2 obj2;
// Base class
class base public:
{ void setk( )
obj1.set(2,3);
protected: {
int i, j; k=i*j; //legal obj1.show( );
void set (int a,int b) } obj1.setk( );
{ void showk( ) obj1.showk( );
i=a; {
j=b; cout<<k; }
} }; obj2.set(3,4);
void show( ) class derived2: public derived 1 obj2.show( );
{ { obj2.setk( );
cout<<i<<j; int m; obj2.showk( );
} obj2.setd( );
}; public: obj2.showd( );
void setd( )
{
m=i-j; // legal
} }
void showd( )
{
cout<<m; }
}; 10
• Object of derived1 can access public and
protected members of base class within its
own member functions.
• &
• Object of derived2 can access member
functions of derived2 + public and protected
members of base class and derived1 class.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 11
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Private Inheritance
• If base class is inherited as private then all protected
and public members of base class will act as
private members of derived class.
• Public and protected members of base class will act
as private members of derived class which means
they would not be accessible by deived2 or outside
derived1.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example Program
#include<conio.h> class derived1: private base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class
class base public:
{ void setk( )
protected: {
int i, j; k=i*j; // legal b/c I & j are private members to
public: derived class and can be used within
void set (int a,int b) derived class.
{ }
i=a; void showk( )
j=b; {
} cout<<k; }
void show( ) };
{
cout<<i<<j;
}
};
3
int main( )
{
derived1 obj;
illegal b/c set( ) & show( ) are
obj.set(2,3); private members of derived class
obj.show( ); and can not be accessed outside
derived class
obj.setk( );
obj.showk( );
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Accessing Private Members
• Now private members can be accessed through public interface
of derived class.
#include<conio.h> class derived1: private base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class void Set(int a, int b) and void
class base public:
{ void setk( )
show( ) are public members of
protected: { base class but private
int i, j; set(10,20); members of derived class and
public: k=i*j; cannot be accessed outside
void set (int a,int b) } So
{ void showk( ) These private members are
i=a; { accessed in public functions
j=b; show( );
} cout<<k; }
so that we can call them from
void show( ) }; main function by calling setk( )
{ and sshowk( )
cout<<i<<j;
}
}; C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
• int main( )
• {
• derived obj; illegal because it is a private
• member of derive class
• obj.set(10,20);
•
• obj.setk( );
• obj.showk( ); Legal because both are
• public members
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Practice Question
• Write a class LocalPhone that contains an attribute phone to
store a local telephone number. The class contains member
functions to input and display phone number.
• Write a child class NatPhone for national phone numbers that
inherits LocPhone class. It additionally contains an attribute to
store city code. It also contains member functions to input and
show the city code.
• Write another class InPhone for international phone numbers
that inherits NaatPhone class. It additionally contains an
attribute to store country code. It also contains member
functions to input and show the country code.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Protected Inheritance
• If base class is inherited as protected then all
protected and public members of base class will act
as protected members of derived class.
• Syntax:
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example
#include<conio.h> class derived1: protected base
#include<iostream> {
usingnamespace std; // i & j are inherited as protected
int k;
// Base class
class base public:
{ void setk( )
protected: { Public and protected members
int i, j; set(10,20); of base class become
public: k=i*j;
void set (int a,int b) }
protected member of derived
{ void showk( ) class and except second
i=a; { derived class we can not
j=b; show( ); access protected members
} cout<<k; } outside the class.
void show( ) }; So we will access this
{ protected member through
cout<<i<<j;
}
public interface functions
}; Setk( ) and showk( )
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
• int main( )
• {
• derived1 obj; illegal because it is a
• protected member of derive
• obj.set(10,20); class
•
• obj.setk( );
• obj.showk( ); Legal because both are
• public members
• }
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example Program2:
#include<conio.h> class derived1: protected base int main( )
#include<iostream> { {
usingnamespace std; protected :
int k; derived2 obj2;
// Base class public:
class base void setk( )
obj2.setk( );
{ {
obj2.showk( );
protected: set(20,30);
int i, j; obj2.setd( );
k=i*j; //legal
void set (int a,int b) } obj2.showd( );
{ void showk( ) return 0;
i=a; {
j=b; cout<<k; } }
} };
void show( ) class derived2: public derived 1
{ {
cout<<i<<j; int m;
}
}; public:
void setd( )
{
set(10,20);
m=i-j; // legal
}
void showd( )
{
show( );
cout<<m; } }; 5
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Pointer to Objects
• The member of a class can be accessed
through the pointer to the class.
• The arrow symbol (->) is also known as
member access operator.
• It is denoted by a hyphen(-) and a greater than
sign (>).
• The general syntax to access a member of a
class through its pointer “P” is:
P -> class member;
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Example:
#include<iostream> int main()
#include<conio.h> {
using namespace std; ptr * p;
ptr o;
class ptr p=&o;
{ p->input();
private: p->show();
char name[15]; getch();
int age; return 0;
public: }
void input()
{
cout<<"Enter Name & Age";
cin>>name>>age;
}
void show()
{
cout<<"Name="<<name<<endl;
cout<< "Age="<<age;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 3
Pointer to Derived Types
• If a pointer object is defined to point to a class then it can
also point to any of its subclass.
• However, even if the pointer points to an object of its derived
class, it remains of base class type.
• Although we can use a base pointer to point to a derived
object, we can access only the members of the derived type
that were inherited from the base.
• That is, we won’t be able to access any member added by
the derived class.
• This is the default method of execution of a member function
through a pointer.
• A pointer of derived type may not point to base type
object.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 4
Example
include<iostream> int main()
#include<conio.h>
using namespace std;
{
base *bp;
class base
{ derived d;
int i;
public:
void set(int num) bp=&d; // base pointer points to derived object
{
i=num; bp->set(10); // accessing derived object using base pointer
}
int get()
{ cout<<bp->get(); // accessing only members of derived type that
return i; were inherited from the base
}
};
class derived: public base bp->set(d10); // Error
{
int j; cout<<bp->getd(); //Error
public:
void setd(int num)
return 0;
{ }
j=num;
}
int getd()
{
return j;
}
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 5
OBJECT ORIENTED PROGRAMMING(CS-1201)
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 1
Early Binding
• The events that take place at the compile time are called early
binding.
• It is also called static binding.
• In essence , early binding occurs when all the information needed
to call a function is known at the compile time.
• Accessing member functions of class through the pointer is an
example of early binding.
• In the previous example the compiler decides at compile time to
always execute the member function of the class whose type
matches the type of pointer irrespective of the contents of the
pointer.
• Thus whatever the object points to during execution of the
program, the pointer always access the member of the class
whose type matches with its type.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 2
Polymorphism
• Poly means many and morphism means forms
or shapes.
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 6
Example
#include<conio.h> class derived : public base { int main()
#include <iostream> public: {
using namespace std; void print() base* bptr;
{ derived d;
class base { cout << "print derived bptr = &d;
public: class" << endl;
virtual void print() } // virtual function, binded at
{ runtime
cout << "print base void show() bptr->print();
class" << endl; {
} cout << "show derived // Non-virtual function,
class" << endl; binded at compile time
void show() } bptr->show();
{ };
cout << "show base getch();
class" << endl; return 0;
} }
};
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 7
Practice Question
• Create a base class called shape. Use this class to store two double type
values that could be used to compute the area of figures.
• Derive two specific classes called triangle and rectangle from the base
shape. Add to the base class, a member function get_data ( ) to initialize
base class data members and another member function display_area ( ) to
compute and display the area of figures.
• Make display area ( ) as a virtual function and redefine this function in
the derived classes to suit their requirements.
• Using these three classes, design a program that will accept dimensions
of a triangle or a rectangle interactively and display the area. Remember
the two values given as input will be treated as lengths of two sides in
the case of rectangles and as base and height in the case of triangles and
used as follows:
• Area of rectangle = x * y
• Area of triangle = ½ * x * y
C++ How to Program by Paul Deitel & Harvey Deitel, Eighth Edition 8