







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!








Without Using Virtual Keyword #include<iostream.h> class base { public: void getdata(); void display(); }; class derivedB: public base { private: long int rollno; char name[20]; public: void getdata(); void display(); }; void base::getdata() { cout<<"base class getdata function"; } void base::display() { cout<<"base class display function"; } void derivedB::getdata() { cout<<"Enter the name"<<endl; cin>>name; cout<<"Enter the roll no"<<endl; cin>>rollno; } void derivedB::display() { cout<<"The name is"<<name<<endl; cout<<"The roll no is"<<rollno<<endl; } void main() { clrscr(); base *ptr; derivedB obj; ptr=&obj; ptr->getdata(); ptr->display(); getch(); }
(^) It provide a way for a program to decide, when it is running, what function to call. (^) It allows greater flexibility in performing the same kinds of action on different kinds of objects. (^) It actually holds pointers to a variety of derived types (^) It is defined and declared in the base class and is then used by several derived functions by getting up pointers.
With Using “virtual” Keyword #include<iostream.h> #include<conio.h> class base { public: virtual void getdata()=0; virtual void display()=0; }; class derivedB: public base { private: long int rollno; char name[20]; public: void getdata(); void display(); }; void derivedB::getdata() { cout<<"Enter the name"<<endl; cin>>name; cout<<"Enter the roll no"<<endl; cin>>rollno; } void derivedB::display() { cout<<"The name is"<<name<<endl; cout<<"The roll no is"<<rollno<<endl; } void main() { clrscr(); base *ptr; derivedB obj; ptr=&obj; ptr->getdata(); ptr->display(); getch(); }
(^) This function should be declared in the base class specifications (^) It can be overloaded (^) It should be a member function of a class (^) There can be virtual destructors (^) Constructors cannot be declared as virtual functions (^) This function may or may not have function body (^) It cannot be an ordinary stand alone function (^) These functions are to be accessed by base class pointers (^) If there is no code defined for a virtual function in derived class, then base class function is invoked
Polymorphism Using Array #include<iostream.h> #include<conio.h> class base { public: virtual void show()=0; }; class base1:public base { public: void show(){ cout<<"\n base1 called";} }; class base2:public base { public: void show(){ cout<<"\n base2 called"; } };
Abstract classes A class that contains atleast one pure virtual function is said to be an abstract class. NOTE : you can use an abstract class only act as a base class for deriving other classes but does not create objects #include<iostream.h> #include<conio.h> class book { private : int x; public : book() { x=0; } virtual void getdata()=0; virtual void putdata()=0; }; void main() { clrscr(); cout<<"end"; getch(); }