Virtual Class Base Examples :)
1) Simple Example of virtual class
#include<fstream.h>
#include<conio.h>
class base
{
public:
virtual void show()=0;
};
class derived1 : public base
{
public:
void show()
{
cout<<"\n Mahi 1";
}
};
class derived2 : public base
{
public:
void show()
{
cout<<"\n Mahi 2";
}
};
void main()
{
clrscr();
base *b;
derived1 d1;
derived2 d2;
b = &d1;
b->show();
b = &d2;
b->show();
getch();
}
Here is the output :)
2) Virtual class example of student details
#include<conio.h>
#include<iostream.h>
class base
{
public:
virtual void input()=0;
virtual void output()=0;
};
class derived:public base
{
char name[15];
int roll_no,age;
public:
void input()
{
cout<<"Enter name of the student: ";
cin>>name;
cout<<"Enter roll no of the student: ";
cin>>roll_no;
cout<<"Enter age of the student: ";
cin>>age;
}
void output()
{
cout<<"Name: "<<name<<endl;
cout<<"Roll no: "<<roll_no<<endl;
cout<<"Age: "<<age<<endl;
}
};
void main()
{
base *ptr;
derived d1;
clrscr();
ptr=&d1;
ptr->input();
cout<<"Data of student is: "<<endl;
ptr->output();
getch();
}
Here is the output :)
No comments:
Post a Comment