4/24/2016

Virtual and nonvirtual function in oop with c++

TOPICS:-
Virtual and non virtual function
Pure virtual function
run time and compile time binding


This programming includes following features:-

     nonvirtual function
     using compile time binding




#include<iostream>
 using namespace std;
class test
 {
public:
void display()
{
cout<<"It is a base class.\n";
}
};

 class derived1:public test
 {
public:
void display()
{
cout<<"It is the first derived class.\n";
}
};
 class derived2:public test
{
public:
void display()
 {
cout<<"It is the second derived class.\n";
 }
};
 int main()
 {
test aaa;
 derived1 bbb;
derived2 ccc;
 test *str[3];
str[0]=&aaa;
str[1]=&bbb;
str[2]=&ccc;
str[0]->display();
str[1]->display();
str[2]->display();
return 0;
 }

Output:
It is a base class.
It is a base class.
It is a base class.


 -----------------------------------------
This programming describes-
*difference between virtual function and non virtual function
*run time binding and compile time binding.


#include<iostream>
using namespace std;
class test
{
public:
void display()
{
cout<<"It is a base class.\n";
}

virtual void print()
{
cout<<"Welcome to base class.\n";
}
};

class derived1:public test
{
public:
void display()  //compile time binding
{
cout<<"It is the first derived class.\n";
}

virtual void print()  //run time binding
{
cout<<"Welcome to derived class derived1.\n";
}
};


class derived2:public test
{
public:
void display()
{
cout<<"It is the second derived class.\n";
}

virtual void print()
{
cout<<"Welcome to derived class derived2.\n";
}
};

int main()
{
test aaa;
derived1 bbb;
derived2 ccc;
test *str[3];
str[0]=&aaa;
str[1]=&bbb;
str[2]=&ccc;

for(int i=0;i<=2;i++)
{
str[i]->display();
str[i]->print();
}
return 0;
}


Output:
It is a base class.
Welcome to base class.
It is a base class.
Welcome to derived class derived1.
It is a base class.
Welcome to derived class derived2.
--------------------------------------------------------------





CLICK FOR SEARCH TOPIC


Please just write a comment in comment box.




No comments:

Post a Comment