473,395 Members | 1,578 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

why virtual functions are used in c++?

i want clear explanation for virtual functions in c++.

why virtual functions are used ?

diff b/w non-virtual and virtual functions?
Jul 3 '07 #1
1 2505
weaknessforcats
9,208 Expert Mod 8TB
A normal function is linked in your program at compile time so when your program executes, the function will be called.

You have no ability to change the function call while the program is running.

This is kinda bad where you have a sort that needs to sort in various sequences that won't be known until the user enters choices from the keyboard.

Enter the function pointer.

A function pointer is a pointer that contains the address of a function.

With this in mind, assume you have this:
Expand|Select|Wrap|Line Numbers
  1. class Shape
  2. {
  3.     public:
  4.        void draw() {cout << "I am a Shape" << endl;}
  5. };
  6. class Circle : public Shape
  7. {
  8.     public:
  9.        void draw() {cout << "I am a Circle" << endl;}
  10.  
  11. };
  12.  
  13. void Process(Shape& s)
  14. {
  15.         s.draw();
  16. }
  17.  
  18. int main()
  19. {
  20.       Circle c;
  21.       Process(c);
  22. }
  23.  
What you will see is the call to Process uses a derived object. The Process() function can accept this because a Circle IS-A Shape. However, when
s.draw() is called you see "I am a Shape" because Process() believes it has a Shape object.

This is not the desired output.

If you make the draw() function virtual, the compiler is told that if it has a choice between Shape::draw() or Circle::draw(), then you want to call Circle::draw().

To make this happen, a run-time decision needs to be made inside Process() to call the correct draw() function. That means a function pointer needs to be selected. The compiler accomplishes by building a table of function pointers for the virtual functions of a class and then placing the address of the table (called the VTBL) inside the object.

Then anytime the object is used and a virtual function is needed, the compiler generates code to look the function up in the VTBL and call it by address. All of this is hidden from you.

The effect is that you now see "I am a Circle" inside Process() because it is a Circle object that is really being used and the draw() is virtual so the address of the draw() is looked up in the VTBL. What is there is Circle::draw() because Circle overrode the Shape draw() method.

In effect, a virtual function is how C++ implements polymorphism.

Using polymorphism is commonly call Object-Oriented Programming.
Jul 3 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: vijay | last post by:
I have a doubt with size of classed with virtual functions I have declared A,A1,A2 ,B , C, D some classes with no varaibles but a vitual function each, The size of A is as expected 4 bytes with...
15
by: Dave Townsend | last post by:
Yo, I had a job interview today, the interviewing asked me about inline virtual functions, or what was my opinion on them. Hm, I've seen mention of these babies in the reference material, but...
25
by: Stijn Oude Brunink | last post by:
Hello, I have the following trade off to make: A base class with 2 virtual functions would be realy helpfull for the problem I'm working on. Still though the functions that my program will use...
23
by: heted7 | last post by:
Hi, Most of the books on C++ say something like this: "A virtual destructor should be defined if the class contains at least one virtual member function." My question is: why is it only for...
11
by: santosh | last post by:
Hello, I was going through the Marshal Cline's C++ FAQ-Lite. I have a doubt regarding section 33.10. Here he is declaring a pure virtual destructor in the base class. And again defining...
20
by: Nemanja Trifunovic | last post by:
Something I don't get it: Say we have: ref class Base { virtual void SomeVirtualFunction() {Console::WriteLine(L"Base");} public: void SomeAccessibleFunction() {SomeVirtualFunction();}
3
by: Pravesh | last post by:
Hello All, I had some query regarding virtual functions/destructors. If a class is having some/all of its methods that are virtual then is it recommended that it should also have virtual...
7
by: eric | last post by:
hello i'm confused by an example in the book "Effective C++ Third Edition" and would be grateful for some help. here's the code: class Person { public: Person(); virtual ~Person(); // see...
14
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
17
by: Jess | last post by:
Hello, If I have a class that has virtual but non-pure declarations, like class A{ virtual void f(); }; Then is A still an abstract class? Do I have to have "virtual void f() = 0;"...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.