Question:
Why we need virtual functions in c++?
?
2012-04-14 22:46:11 UTC
i want to know the concept of virtual functions and the requirement of it...
Three answers:
Rohit
2012-04-15 10:55:00 UTC
Hi..



1. Virtual Functions are used to support " Run time Polymorphism".



2. You can make a function virtual by preceeding its declaration within the class by keyword 'virtual'.



3. When a Base Class has a virtual member function, any class that inherits from the Base Class can redefine the function with exactly the same prototype i.e. only functionality can be redefined, not the interface of the function.



4. A Base class pointer can be used to point to Base Class Object as well as Derived Class Object.



5. When the virtual function is called by using a Base Class Pointer, the Compiler decides at Runtime which version of the function i.e. Base Class version or the overridden Derived Class version is to be called. This is called Run time Polymorphism.



Hope it helps...
?
2016-10-22 01:17:33 UTC
the region is because, once you're making study() interior the ROM classification secure you eliminate it is visibility from the exterior of the category. you may purely get ideal of entry to secure contributors once you're the category itself, or a classification derived from that classification. the numerous() function is neither of those so can purely call approaches on the ROM classification that are public. The CD classification's study() function may nonetheless be callable from significant through a form solid, e.g. (dynamic_cast(disk))->study(), yet you won't be able to get ideal of entry to that function from the bottom classification pointer because it is not publicly seen interior the bottom classification.
2012-04-14 23:03:46 UTC
I believe the best way is for me to show you: http://pastebin.com/5dXq6GgD <
I quickly threw this together but as you can see the output for d->eat() is "Animal Eats" and the reason for that is because its not a virtual function. Try running this code yourself and you will see. I commented what it says.



Here: http://ideone.com/95vKt I ran the code in Ideone for you. If you don't understand then give me an email on my profile page.



--------------------

#include

#include



using namespace std;



class Animal{

public:

Animal(){



}

void eat(){

cout<<"Animal Eating\n";

}

virtual void sleep(){

cout<<"Animal Sleeping\n";

}

};

class Dog : public Animal{

public:

Dog():Animal(){



}

void eat(){

cout<<"Dog Eating\n";

}

virtual void sleep(){

cout<<"Dog Sleeping\n";

}



};



int main(int argc, char** argv) {

Animal *a = new Animal();

Animal *d = new Dog();

Dog *dptr = (Dog *)d;

a->eat(); //Animal Eating

a->sleep(); //Animal Sleeping

d->eat(); //Animal Eating

d->sleep(); //Dog Sleeping

dptr->eat(); //Dog Eating

dptr->sleep();//Dog Sleeping

return 0;

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...