You are on page 1of 38

Object Oriented Programming

BSE II

Lecture 06

Instructor: Bushra Bashir Chaoudhry

 An object represents an individual, identifiable item, unit, or entity, either real


or abstract, with a well-defined role in the problem domain.

Or

 An "object" is anything to which a concept applies.

 Modularity - large software projects can be split up in smaller pieces.

 Reusability - Programs can be assembled from pre-written software


components.

 Extensibility - New software components can be written or developed from


existing ones.

 Object = Data + Methods

 or to say the same differently:

 An object has the responsibility to know and the responsibility to do.

 Abstraction is the representation of the essential features of an object.


These are ‘encapsulated’ into an abstract data type.

 Encapsulation. There should be tight coupling between data and methods


that operate on this data. Such data should be hidden from the code outside
the current context. This process of data hiding and combining data and
methods in a single logical unit is called encapsulation. The internal state is
usually not accessible by other objects.

 Inheritance means that one class inherits the characteristics of another


class.
This is also called a “is a” relationship:

 A car is a vehicle

 Polymorphism

 Functionality name remains the same, while the implementation varies


across different parent and child classes.
 Poly= many

 Morph=faces

 Classes

 A class is an expanded concept of a data structure: instead of holding only


data, it can hold both data and functions.

 The data and methods that operate on this data are encapsulated in a single
package called “calss”.

 An object is an instantiation of a class. In terms of variables, a class would


be the type, and an object would be the variable.

 Classes are generally declared using the keyword class, with the following
format:

class class_name

access_specifier_1:

member1;

access_specifier_2:

member2;

... } object_names;

 class_name is a valid identifier for the class .

 object_names is an optional list of names for objects of this class.

 The body of the declaration can contain members, that can be either data or
function declarations, and optionally access specifiers.

 All is very similar to the declaration on data structures except

 that we can now include also functions and data members.

 but also this new thing called access specifier

 “An access specifier is one of the following three keywords: private,


public or protected. “

 private members of a class are accessible only from within other members
of the same class or from their friends.
 protected members are accessible from members of their same class and
from their friends, but also from members of their derived classes.

 public members are accessible from anywhere where the object is visible.

 N.B: All members of a class declared with the class keyword have private
access for all its members.

class CRectangle

int x, y;

public:

void set_values (int,int);

int area (void);

} rect;

 This class contains four members: two data members of type int (member x
and member y) with private access and two member functions with public
access: set_values() and area(), we have only included their declaration, not
their definition.

 #include <iostream>

 using namespace std;

 class CRectangle

 {

 int x, y;

 public:

 void set_values (int a, int b)

 {

 x = a;

 y = b;

 }

 } int area ()
 {

 return (x*y);

 }

 };

 int main ()

 {

 CRectangle rect;

 rect.set_values (3,4);

 cout << "area: " << rect.area();

 return 0;

 }

 #include <iostream>

 using namespace std;

 class CRectangle

 {

 int x, y;

 public:

 void set_values (int,int);

 int area ()

 {

 return (x*y);

 }

 };

 void CRectangle::set_values (int a, int b)

 {

 x = a;
 y = b;

 }

 int main ()

 {

 CRectangle rect,rect1;

 rect.set_values (3,4);

 rect.set_values (5,6);

 cout << "area: " << rect.area();

 cout << "area: " << rect1.area();

 return 0;

 }

 the definition of the member function area() has been included directly within
the definition of the CRectangle class.

 set_values() has only its prototype declared within the class, but its definition
is outside it.

 In outside declaration, we must use the operator of scope (::) to specify that
we are defining a function that is a member of the class CRectangle and not a
regular global function.

 The scope operator (::) specifies the class to which the member being
declared belongs, granting exactly the same scope properties as if this
function definition was directly included within the class definition.

 One of the greater advantages of a class is that, as any other type, we can
declare several objects of it. e.g.

CRectangle rect,rect1;

 rect and rect1has its own member variables and member functions.

 Call to rect.area() does not give the same result as the call to rect1.area().

 each object of class CRectangle has its own variables x and y.

 The also have their own function members set_value() and area() that
each uses its object's own variables to operate.
 That is the basic concept of object-oriented programming:

 Data and functions are both members of the object. We no longer use sets of
global variables that we pass from one function to another as parameters,
but instead we handle objects that have their own data and functions
embedded as members.

 N.B: We have not had to give any parameters in any of the calls to
rect.area() or rect1.area(). Those member functions directly used the data
members of their respective objects rect and rect1.

 Object Oriented Programming

 BSE II

 Lecture 07

 Instructor: Bushra Bashir Chaoudhry

 In C++ two different functions can have the same name if their parameter
types or number are different.

 Such functions are called “Overloaded Functions”.

 #include <iostream>

 using namespace std;

 int operate (int a, int b)

 {

 return (a*b);

 }

 float operate (float a, float b)

 {

 return (a/b);

 }

 int main ()

 {

 int x=5,y=2;

 float n=5.0,m=2.0;
 cout << operate (x,y);

 cout << "\n";

 cout << operate (n,m);

 cout << "\n";

 return 0;

 }

 #include <iostream>

 using namespace std;

 class CRectangle

 {

 int x, y;

 public:

 void set_values (int,int);

 int area ()

 {

 return (x*y);

 }

 };

 void CRectangle::set_values (int a, int b)

 {

 x = a;

 y = b;

 }

 int main ()

 {

 CRectangle rect,rect1;
 rect.set_values (3,4);

 rect.set_values (5,6);

 cout << "area: " << rect.area();

 cout << "area: " << rect1.area();

 return 0;

 }

 Objects generally need to initialize variables or assign dynamic memory


during their process of creation to become operative and to avoid returning
unexpected values during their execution.

 What would happen if in the previous example we called the member


function area() before having called function set_values() ?

 Probably we would have gotten an undetermined result since the


members x and y would have never been assigned a value.

 In order to avoid that, a class can include a special function called


constructor, which is automatically called whenever a new object of this class
is created.

 This constructor function must have the same name as the class, and
cannot have any return type; not even void.
“A class method having the same name as the class name is called the
class constructor.”

 #include <iostream>

 using namespace std;

 class CRectangle

 {

 int width, height;

 public:

 CRectangle (int,int);

 int area ()

 {

 return (width*height);
 }

 };

 CRectangle::CRectangle (int a, int b)

 {

 width = a;

 height = b;

 }

 int main ()

 {

 CRectangle rect (3,4);

 CRectangle *rectb = new CRectangle(5,6);

 cout << "rect area: " << rect.area() << endl;

 cout << "rectb area: " << rectb->area() << endl;

 return 0;

 }

 we have removed the member function set_values(), and have included


instead a constructor that performs a similar action.

 It initializes the values of width and height with the parameters that are
passed to it.

CRectangle rect (3,4);

 Passing the arguments to the constructor is also different

CRectangle *rectb = new CRectangle(5,6);

 N.B: rectb is a dynamic object that is created at run time.

 The memory allocation for the CRectangle object recta is done at compile
time, at certain times you will wish to create objects at run time and delete
them as they are no more required by application. This results in better
memory usage.

 To create dynamic objects- new is used.


CRectangle *rectb;

rectb = new Crectangle();

 To delete dynamically created objects- delete is used.


delete rectb;

 Constructors cannot be called explicitly as if they were regular member


functions. They are only executed when a new object of that class is created.

 N.B: Neither the constructor prototype declaration (within the class) nor the
latter constructor definition include a return value; not even void.

 Like any other function, a constructor can also be overloaded with more than
one function that have the same name but different types or number of
parameters.

 include <iostream>

 using namespace std;

 class CRectangle

 {

 int width, height;

 public:

 CRectangle ();

 CRectangle (int,int);

 int area (void)

 {

 return (width*height);

 }

 };

 CRectangle::CRectangle ()

 {

 width = 5;

 height = 5;
 }

 CRectangle::CRectangle (int a, int b)

 {

 width = a;

 height = b;

 }

 int main ()

 {

 CRectangle rect (3,4);

 CRectangle rectb;

 cout << "rect area: " << rect.area() << endl;

 cout << "rectb area: " << rectb.area() << endl;

 return 0;

 }

 rectb was declared without any arguments, so it has been initialized with the
constructor that has no parameters, which initializes both width and height
with a value of 5.

 Object Oriented Programming

 BSE II

 Lecture 08

 Instructor: Bushra Bashir Chaoudhry

 When you create an object, if you do not declare a constructor, the compiler
would create one for your program; this is useful because it lets all other
objects and functions of the program know that this object exists. This
compiler created constructor is called the default constructor.

 #include <iostream>

 using namespace std;

 class Book
 {

 public:

 Book();

 };

 Book::Book()

 {

 cout << "I see a book...\n";

 }

 int main()

 {

 Book B;

 return 0;

 }

 At certain times you may wish to create a copy of an existing object.

 A copy constructor is a special constructor in the C++ programming


language used to create a new object as a copy of an existing object.

 C++ defines two distinct types of situations in

 which the value of one object is given to another.

 The first is assignment.

 The second is initialization.

 Copy constructor is needed when you want to initialize one object with
another, this is done in 3 ways:

 When one object explicitly initializes another, such as in a declaration

myclass x = y; // y explicitly initializing x

 When a copy of an object is made to be passed to a function

func(y); // y passed as a parameter


 When a temporary object is generated (most commonly, as a return
value)

y = func(); // y receiving a temporary, return object

 For initialization create a constructor in your class definition that takes the
object to be copied as an argument.

 N.B: It is permissible for a copy constructor to have additional parameters as


long as they have default arguments defined for them. However, in all cases
the first parameter must be a reference to the object doing the initializing.

 class Point

 {

 public:

 int x,y;

 public:

 Point (int x1,int y1)

 {

 x=x1;

 y=y1;

 cout<<“constructor called”;

 }

 Point (Point &p)

 {

 x=p.x;

 y=p.y;

 cout<<“copy constructor called”;

 }

 };

 void main()

 {
 Point p1(5,5);

 cout<<“Point p1 (“<<p1.x<<“,”<<p1.y<<“)”<<endl;

 Point p2(p1);

 cout<<“Point p2 (“<<p2.x<<“,”<<p2.y<<“)”<<endl;

 cout<<“Setting data members of two objects”;

 p1.x=10; p1.y=10;

 p2.x=20;p2.y=20;

 cout<<“Point p1 (“<<p1.x<<“,”<<p1.y<<“)”<<endl;

 cout<<“Point p2 (“<<p2.x<<“,”<<p2.y<<“)”<<endl;

 }

 The destructor fulfills the opposite functionality.

 It is automatically called

 When an object is destroyed, either because its scope of existence has


finished (for example, if it was defined as a local object within a
function and the function ends)

 When an object dynamically assigned and it is released using the


operator delete.

 The destructor must have the same name as the class, but preceded with a
tilde sign (~) and it must also return no value.

 #include <iostream>

 using namespace std;

 class CRectangle

 {

 int *width, *height;

 public:

 CRectangle (int,int);

 ~CRectangle ();
 int area ()

 {

 return (*width * *height);

 }

 };

 CRectangle::CRectangle (int a, int b)

 {

 width = new int;

 height = new int;

 *width = a;

 *height = b;

 }

 CRectangle::~CRectangle ()

 {

 delete width;

 delete height;

 }

 int main ()

 {

 CRectangle rect (3,4);

 CRectangle rectb (5,6);

 cout << "rect area: " << rect.area() << endl;

 cout << "rectb area: " << rectb.area() << endl;

 return 0;

 }
 It is especially suitable when an object assigns dynamic memory during its
lifetime and at the moment of being destroyed we want to release the
memory that the object was allocated.

 In principle, private and protected members of a class cannot be accessed


from outside the same class in which they are declared. However, this rule
does not affect friends.

 A friend function is used for accessing the non-public members of a class. A


class can allow non-member functions and other classes to access its own
private data, by making them friends.

 A friend function can be an ordinary function or a member of another class.

 If we want to declare an external function as friend of a class. We do it by

 declaring a prototype of this external function within the class,

 preceding it with the keyword friend.

 It is possible to declare a function as friend in any number of classes.

 It is possible to declare the friend function as either private or public.

 The function can be invoked without the use of an object. The friend function
has its argument as objects.

 #include<iostream>

 #include<conio.h>

 using namespace std;

 class Bank

 {

 int a,b;

 public:

 void test()

 {

 a=100;

 b=200;

 }
 friend int backdoorCall(Bank b1);

 };

 int backdoorCall(Bank b1)

 {

 cout<<"backdoor can access variable of object b1 whose value is "<<b1.a;

 return b1.a;

 }

 main()

 {

 Bank b1;

 b1.test();

 cout<<"The result is:"<<

 backdoorCall(b1);

 getch(); return 0;

 }

 Object Oriented Programming

 BSE II

 Lecture 09

 Instructor: Bushra Bashir Chaoudhry

 Inheritance is a form of software reuse in which the programmer creates a


class that absorbs an existing class's data and behaviors and enhances them
with new capabilities.

 Software reusability saves time during program development.

 It also encourages the reuse of proven, debugged, high-quality


software.

 It increases the likelihood that a system will be implemented


effectively.
 When creating a class, instead of writing completely new data members and
member functions, new class can inherit the members of an existing class.

 This existing class is called the base class, and the new class is referred to
as the derived class.

 A derived class represents a more specialized group of objects.

 A direct base class is the base class from which a derived class explicitly
inherits. An indirect base class is inherited from two or more levels up in
the class hierarchy.

Base class Derived classes

Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle, Sphere, Cube

Employee Faculty, Staff

Account CurrentAccount, SavingsAccount

// derived classes

#include <iostream>

using namespace std;

class CPolygon

protected:

int width, height;

public:

void set_values (int a, int b)

width=a; height=b;

} };

class CRectangle:public CPolygon


{

public:

int area ()

return (width * height);

} };

class CTriangle: public CPolygon

public: int area ()

{ return (width * height / 2);

} };

int main ()

CRectangle rect;

CTriangle trgl;

rect.set_values (4,5);

trgl.set_values (4,5);

cout << rect.area() << endl;

cout << trgl.area() << endl;

return 0;

 Every derived-class object is an object of its base class, and one base class
can have many derived classes.

 The set of objects represented by a base class typically is larger than the set
of objects represented by any of its derived classes.

 Inheritance relationships form treelike hierarchical structures. A base


class exists in a hierarchical relationship with its derived classes.
class DerivedClassName : AcessModifier BaseClassName

 A base class's public members are accessible within the body of that base
class and anywhere that the program has a handle (i.e., a name, reference or
pointer) to an object of that base class or one of its derived classes.

 A base class's private members are accessible only within the body of that
base class and the friends of that base class.

 protected access offers an intermediate level of protection between public


and private access.

 A base class's protected members can be accessed within the body of


that base class, by members and friends of that base class, and by
members and friends of any classes derived from that base class.

 class A

 {

 int x,y;

 protected:

 void setx (int x1)

 {

 x=x1;

 }

 int getx();

 {

 return x;

 }

 public:

 void sety (int y1);

 int gety();

 };

 class B: public A

 {
 public:

 int getXCoordinate()

 {

 return getx();

 }

 void setXCoordinate(int x)

 {

 setx (x);

 }

 }

 void main()

 {

 cout<< “Creating subclass object”<<endl;

 B objectB;

 cout <<“Calling protected setx method indirectly”<<endl;

 objectB.setXCoordinate(10);

 cout <<“Calling protected getx method indirectly”<<endl;

 int x=objectB.getXCoordinate();

 cout<<“x= “ << x<<endl;

 }

 Multi Level Inheritance

 It is possible to extend the functionality of a derived class by deriving further


classes from it.

class A

int x,y;

protected:
void setx (int x1)

x=x1;

int getx();

return x;

public:

void sety (int y1);

int gety();

};

class B: public A

};

class C: public B

};

Kinds of Inheritance

 C++ offers three kinds of inheritance

 Public

 Protected

 Private

 Public: When a base class is specified as

class c : public base {};


 In public inheritance the derived class has access to all the public methods
and data members of the base class. The derived class can not access the
private methods and data members of the base class.

 With public inheritance, every object of a derived class is also an object of


that derived class's base class. However, base-class objects are not objects of
their derived classes.

 For example, if we have vehicle as a base class and car as a derived class,
then all cars are vehicles, but not all vehicles are cars.

 When deriving from a protected base class, public and protected members
of the base class become protected members of the derived class.

 When deriving from a private base class, public and protected members of
the base class become private members of the derived class.

 class Student

 {

 private: firstName;

 protected: lastName;

 public: rollNumber;

 };

 class BSEStudent : private Student

 {

 };

 class BSEStudent : protected Student

 {

 };

 class BSEStudent : public Student

 {

 };

 Object Oriented Programming

 BSE II
 Lecture 10

 Instructor: Bushra Bashir Chaoudhry

 Arrays of Objects

 The syntax for declaring and using an object array is exactly the same as it is
for any other type of array.

 For example, the program on following slide uses a three-element array of


objects:

 #include <iostream>

 using namespace std;

 class cl {

 int i;

 public:

 void set_i(int j) { i=j; }

 int get_i() { return i; }

 };

 int main()

 {

 cl ob[3];

 int i;

 for(i=0; i<3; i++) ob[i].set_i(i+1);

 for(i=0; i<3; i++)

 cout << ob[i].get_i() << "\t";

 return 0;

 }

 OUTPUT: 1 2 3

 Initialization of Array of Objects


 If a class defines a parameterized constructor, you may initialize each object
in an array by specifying an initialization list, just like you do for other types
of arrays.

 The exact form of the initialization list will be decided by the number of
parameters required by the object's constructor function.

 For objects whose constructors have only one parameter, you can simply
specify a list of initial values, using the normal array-initialization syntax.

 As each element in the array is created, a value from the list is passed to the
constructor's parameter.

 #include <iostream>

 using namespace std;

 class cl {

 int h;

 int i;

 public:

 cl(int j, int k) { h=j; i=k; } // constructor with 2 parameters

 int get_i() {return i;}

 int get_h() {return h;}

 };

 int main()

 {

 cl ob[3] = {

 cl(1, 2), // initialize

 cl(3, 4),

 cl(5, 6)

 };

 int i;

 for(i=0; i<3; i++) {


 cout << ob[i].get_h();

 cout << ", ";

 cout << ob[i].get_i() << "\n";

 }

 return 0;

 }

 Pointers to Objects

 Just like other variables you can have pointers to objects. When accessing
members of a class given a pointer to an object, use the arrow(->)Operator
instead of the dot operator.

 #include <iostream>

 using namespace std;

 class cl {

 int i;

 public:

 cl(int j) {

 i=j;

 }

 int get_i() {

 return i;

 }

 };

 int main()

 {

 cl ob(99);

 cl *p;

 p=&ob;
 cout<<p->get_i();

 }

 The this pointer is used as a pointer to the class object by the member
function.

 The address of the class instance is passed as an implicit parameter to the


member functions.

 It is a common knowledge that C++ keeps only one copy of each member
function and the data members are allocated memory for all of their
instances. This kind of various instances of data are maintained using this
pointer.

 class student

 {

 int rollNo;

 public:

 student(int roll_no)

 {

 rollNo=roll_no;

 }

 void display()

 {

 cout<<this->rollNo;

 }

 };

 main()

 {

 student s1 (50),s2(30);

 s1.display();

 s2.display();
 getch();

 }

 class this_pointer_example // class for explaining C++ tutorial


{
int data1;
public:
//Function using this pointer for C++ Tutorial
int getdata()
{
return this->data1;
}
//Function without using this pointer
void setdata(int newval)
{
data1 = newval;
}
};

 Two dynamic allocation operators: new and delete.

 These operators are used to allocate and free memory at run time.

 The new operator allocates memory and returns a pointer to the start of it.

 The delete operator frees memory previously allocated using new.

 The general forms of new and delete are shown here:

type *p_var;

p_var = new type;

delete p_var;

#include <iostream>

#include <new>

using namespace std;

int main()

int *p;

try {
p = new int; // allocate space for an int

} catch (bad_alloc xa) {

cout << "Allocation Failure\n";

return 1;

*p = 100;

cout << "At " << p << " ";

cout << "is the value " << *p << "\n";

delete p;

return 0;

• You can initialize allocated memory to some known value by putting an


initializer after the type name in the new statement.

• Here is the general form of new when an initialization is included:

p_var = new var_type (initializer);

• The type of the initializer must be compatible with the type of data for which
memory is being allocated.

• You can allocate arrays using new by using this general form:

p_var = new array_type [size];

• Here, size specifies the number of elements in the array.

• To free an array, use this form of delete:

delete [ ] p_var;

• Here, the [ ] informs delete that an array is being released.

• int main()

• {

• int *p, i;

• try {
• p = new int [10]; // allocate 10 integer array

• } catch (bad_alloc xa) {

• cout << "Allocation Failure\n";

• return 1;

• }

• for(i=0; i<10; i++ )

• p[i] = i;

• for(i=0; i<10; i++)

• cout << p[i] << " ";

• delete [] p; // release the array

• return 0;

• }

• You can allocate objects dynamically by using new. When you do this, an
object is created and a pointer is returned to it.

• The dynamically created object acts just like any other object. When it is
created, its constructor function (if it has one) is called.

• When the object is freed, its destructor function is executed.

• Object Oriented Programming

• MCS II

• Lecture 10

• Instructor: Bushra Bashir Chaoudhry

• An important feature of OOP languages.

• Polymorphism means ‘one name, many forms’.

• e.g

if you have to write a function for printing different data types, you need to
write many different functions and user will be required to remember such functions
during using applications in C like languages, but in C++ you will use only one
function name for all such functions. Each function will have its own independent
implementation. When you call this function with common name, the runtime
decided which implementation to call depending on the current context.

 There are two types of polymorphism

 Static Polymorphism

 It is also called early binding and dynamic

 Dynamic (run time) Polymorphism

 It is also called late binding.

 In this case the compiler resolves at the compile time which implementation
to call for a method having common name. That is why it is called early
binding.

 This is also called compile time polymorphism.

 This type of polymorphism is implemented using function overloading


techniques.

 Function overloading is implemented for

 Normal Function

 Operator Overloaded Functions

 In C++ two different functions can have the same name if their parameter
types or number are different.

 In C++ two different functions can have the same name if their parameter
types or number are different.

 #include <iostream>

 using namespace std;

 int operate (int a, int b)

 {

 return (a*b);

 }

 float operate (float a, float b)

 {

 return (a/b);
 }

 int main ()

 {

 int x=5,y=2;

 float n=5.0,m=2.0;

 cout << operate (x,y);

 cout << "\n";

 cout << operate (n,m);

 cout << "\n";

 return 0;

 }

 Rules of Function Overloading

 All the overloaded functions have same name.

 The number of arguments may differ.

 The data type of arguments may differ.

 The order of arguments may differ.

 The return type differ.

 Merits/Demerits of static polymorphism

 Calls to overloaded methods are resolved at the compile time.

 Helps in creating faster programs.

 it deprives us of the flexibility of plugging the new code at the run


time.

 In this case, the run time environment decides which implementation to call
during the program execution.

 In static polymorphism, for overloaded functions, the compiler resolves which


function to call at compile time but in case of dynamic polymorphism this
decision is delayed until runtime.

 Base Class
 {…

 MyMethod()

 {

 ….

 }

 …

 };

 Derived: Base

 {…

 MyMethod()

 {

 ….

 }

 …

 };

 class Base{

 public:

 void show()

 {

 cout<<"In Base Class Show method" << endl;

 }};

 class Derived: public Base{

 public:

 void show()

 {

 cout<<"In Derived Class Show method" << endl;


 }};

 void main()

 {

 Base base;

 Derived derived;

 cout<<"Using pointer to base class"<<endl;

 Base *baseptr=&base;

 baseptr->show();

 baseptr=&derived;

 baseptr->show();

 cout<<endl;

 cout<<"Using pointer to derived class"<<endl;

 Derived *derivedptr=&derived;

 derivedptr->show();

 derivedptr= (Derived *)&base;

 derivedptr->show();

 cout<<endl;

 }

 Using pointer to base class

 In Base class Show method

 In Base class Show method

 Using pointer to derived class

 In Derived class Show method

 In Derived class Show method

 Virtual Functions

 Virtual function is the solution.


 C++ virtual function is a member function of a class, whose functionality can
be over-ridden in its derived classes. The whole function body can be
replaced with a new set of implementation in the derived class.

 In the base class show method we have to change it as

virtual void show()

OUTPUT

• Using pointer to base class

• In Base class Showmethod

• In Derived class Show method

• Using pointer to derived class

• In Derived class Show method

• In Base class Show method

• When we create a class hierarchy by way of sub-classing, many a times the


base classes are too general to any method implementations.

• The methods declared in the base class are overridden in derived classes.
The derived classes provide the implementation for these methods.

• Rather than providing an empty implementation for the base class methods,
methods are declared as “pure virtual functions”.

• A pure virtual function does not provide the implementation and is declared
as

• virtual void show()=0;

• class Base{

• public:

• virtual void show( ) =0;

• };

• class Derived1: public Base{

• public:

• void show()

• {
• cout<<"In Derived1 Class Show method" << endl;

• }};

• class Derived2: public Base{

• public:

• void show()

• {

• cout<<"In Derived2 Class Show method" << endl;

• }};

• void main()

• {

• Derived1 derived1;

• Derived2 derived2;

• Base *baseptr = &derived1;

• cout<<"Using pointer to Base class"<<endl;

• cout<<“Calling Show method in Derived1 class"<<endl;

• baseptr->show();

• cout<<“Calling Show method in Derived2 class"<<endl;

• baseptr=&derived2;

• baseptr->show();

• cout<<endl;

• }

• Using pointer to base class

• Calling Show method in Derived1 Class

• In Derived1 Show method

• Calling Show method in Derived2 Class

• In Derived2 Show method


• Merits/Demerits of Dynamic Polymorphism

• This type of polymorphism uses late binding.

• Late binding specifies that the call to the function is resolved at


runtime depending on the current context.

• Late binding helps in the development of large applications where code


flexibility is desired.

• By using late binding, code changes can be easily accomplished


without major modifications.

• If a class contains one or more virtual functions, it can not be instantiated,


because there is no implementation provided for a virtual function, the
compiler does not allow you to create an instance of the call containing such
functions, such a class is called “Abstract Class”.

• Then why we need an abstract class?

• Just to create a template on which a class hierarchy may be created.

• Class Base

• {

• public:

• Virtual void Show()=0;

• }

• Class Derived: public Base

• {

• };

• Void main()

• {

• Derived derived;

• }

• Compiler will flag an error as our derived class does not provide any
implementation for the inherited Show method.

• To over come this


• Either you have to provide the implementation of the Show method in
derived class

• Or, you should not attempt to instantiate the Derived class in your
program code.

You might also like