Virtual function vs pure virtual function

Virtual function vs pure virtual function :

Virtual function :-

1. Virtual function have a function body.
2. Overloaded can be done by the virtual funciton. 
(Optional)
3. It is define as : virtual int myfunction();

virtual function example
---code---
class a 
{

public:

virtual void imvirtualmethod()
{
cout<<"Hello";

}

};


class b:public a
{
public:

void imvirtualmethod()
{
cout<<"Nishant";

}

};
// main starts from here

void main()
{

clrscr();

a *ptr;                  

a obj;             // object of class a

b obj1;              // object of class b

ptr = &obj;

p->imvirtualmethod();          //calling virtual method of class a

ptr = &obj1;

ptr->imvirtualmethod();          //calling virtual method of class b
getch();
}

/---code---


Pure virtual function :-
1. Pure virtual function have no function body.
2. Overloading is must in pure virtual funciton. (Must)
3. It is define as : virtual int myfunction() = 0;
4. A class is "abstract class" when it has at least one 
pure virtual function.
5. You cann't create instance of "abstract class", rather 
you have to inherit the "abstract class" and overload all 
pure virtual function.




pure virtual function example



---code---
class a 
{

public:

virtual void imvirtualmethod() = 0; //declaration of pure 
                                          virtual method

};


class b:public a
{
public:

void imvirtualmethod()
{
cout<<"hello";

}

};
 
 
class c:public b
{
public:

void imvirtualmethod()
{
cout<<"Nishant";

}

};
 

 


// main starts from here

void main()
{

clrscr();

a *ptr;                  

c obj;             // object of class c

b obj1;              // object of class b

ptr = &obj;

p->imvirtualmethod();          //calling override virtual
                                     method of class c

ptr = &obj1;

ptr->imvirtualmethod();          //calling override virtual
                                      method of class b
getch();
}

/---code---

Leave an Awesome Comment

comments

About Admin

Nishant Srivastava is a blogger & Software Developer from New Delhi, India. He writes
about Programming Technologies,Gadget Reviews,Website Reviews,Tips and Tricks about Computers,SEO, Technology and Make money online on this Blog.

GeeksTrack.com Runs on Hostgator Hosting!

Geeks Track Strongly Recommends to use Hostgator if you are Planning to start Online Business,The Hostgator Hosting Helps you to build incredible websites with WordPress. Hostgator provides 24x7 Support and Number one hosting provider for hosting Blogs and Websites.

Speak Your Mind

*