473,320 Members | 1,939 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,320 software developers and data experts.

Virtual functions clarifications

180 100+
Hi guys,
I have problem understanding virtual functions??? Like how it works.

My friend asked me some questions

1) What is a static function???
I replied functions to be used without intantiating an object of that class.

2) Can static function be called using this pointer???
I told no!!! but I dont know why??? This is because my funda is not clear.
Need some exaplantion about why???. If possible using day to day life example as like Ganon11 (where I say his explanation for pure virtual functions). It was really good one.

3) What is virtual function???
I know the defination (from book) but the funda is not clear. Please explain with day to day life example .

4) Can virtual functions be made static????

5) Can i call a virtual function from within a constructor????

These are some of the questions I have and I need to make them clear. Please help

Thanks in advance
Mar 15 '07 #1
14 2561
A short reply to some questions (question 3 is quite long to be properly answered, and you can find good explanations both on the web and on books).

1) Your answer is right. And you can use only static and local variables within a static function.

2) Yes, they are class members. But you just have to try to find out.

3) Short answer: they are functions which a derived class can redefine. Then at runtime the "most new" version (i.e., those of the derived class) of the function will be called (unless you explicitly specify which one you are going to call), no matter from where the function is called.
Pure virtual functions (with =0 at the end of the function declaration) are the same as virtual functions, but you don't define them in the base class. You just declare them. Therefore you cannot instantiate objects of the base class, since there are undefined functions.

But there are more details to find out, just google for virtual functions and pure virtual functions.

4) No, I don't know exactly why. But again, just try and find out.

5) Obviously yes, it is a function like all the others.

Sandro
Mar 15 '07 #2
Ganon11
3,652 Expert 2GB
3) Short answer: they are functions which a derived class can redefine. Then at runtime the "most new" version (i.e., those of the derived class) of the function will be called (unless you explicitly specify which one you are going to call), no matter from where the function is called.
Actually, they are functions which a derived class must define. Any derived class can override any base class's function, but it has the option of doing so. Declaring a function as virtual requires subclasses to redefine the function.

At runtime, the 'most new' version is not necessarily the one that is called. For instance, suppose you have two classes, Base and Derived. In Base, you declare a virtual function called function(). Thus, Derived must have function() also. The way you answered, the Derived::function() would always be called, since it is the "most new". But if you have an object of type Base and you call function(), the Base::function() is used. When you call function() on any Base or Derived object, the computer determines which class the object is and uses the appropriate function.
Mar 15 '07 #3
vermarajeev
180 100+
For instance, suppose you have two classes, Base and Derived. In Base, you declare a virtual function called function(). Thus, Derived must have function() also
Are you sure this statement is correct. If yes

Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.   public:
  4.           A(){}
  5.           virtual void func()
  6.           {
  7.              cout<<"A's func()"<<endl;
  8.           }
  9. };
  10.  
  11. class B : public A
  12. {
  13. public:
  14.           B(){}
  15. }; 
  16.  
  17. void userFunc( A* obj )
  18. {
  19.    obj->func();
  20. }
  21.  
  22. int main()
  23. {
  24.    A a;
  25.    B b;
  26.    userFunc( &a );
  27.    return 0;
  28. }
Here class B derived from A doesnt have a function func();

I'm totally confused now....Please guys....
Mar 15 '07 #4
dmjpro
2,476 2GB
hello if the derived class don't override the base class function then the derived class uses the base class version.........
Mar 15 '07 #5
vermarajeev
180 100+
hello if the derived class don't override the base class function then the derived class uses the base class version.........
Hi dmjpro,
Can you please be more specific??? If possible with example given in above post.

Thanks in advance
Mar 15 '07 #6
dmjpro
2,476 2GB
Hi guys,
I have problem understanding virtual functions??? Like how it works.

My friend asked me some questions

1) What is a static function???
I replied functions to be used without intantiating an object of that class.

2) Can static function be called using this pointer???
I told no!!! but I dont know why??? This is because my funda is not clear.
Need some exaplantion about why???. If possible using day to day life example as like Ganon11 (where I say his explanation for pure virtual functions). It was really good one.

3) What is virtual function???
I know the defination (from book) but the funda is not clear. Please explain with day to day life example .

4) Can virtual functions be made static????

5) Can i call a virtual function from within a constructor????

These are some of the questions I have and I need to make them clear. Please help

Thanks in advance

2.because this is silently generated when the object is created .... but in the static function there is no surity of object creation..... so u can't access this from static function.

3.virtual functions are those function which are bound by the run time system at run time.....
if u don't specify a method as virtual then compiler decides to run at compilation time.....

the virual function is manatained by VPTR which silently inserted by Compiler and resolved by run time system

know one thing the static funciton never be inherited so it is virtual does not make any sense.....

u can't call virtual function inside constructor .. because inside the constructor the VPTR mechanism inserted.... i think it may work ... but it is not safe

welcome .....
Mar 15 '07 #7
vermarajeev
180 100+
Wow!!! This is what I wanted... Thanks a lot

I have some more doubts from above.

virtual functions are those function which are bound by the run time system at run time.....
if u don't specify a method as virtual then compiler decides to run at compilation time
So you mean to say, member functions are selected based on type of object rather than pointer/reference to that object.

I would be happy if you could explain me how this VPTR works. Suppose I have a class Base and a class Derived. There are two virtual functions defined in class Base, these two methods are overridden in Derived class. How is that the VPTR comes into picture????

know one thing the static funciton never be inherited so it is virtual does not make any sense.....
This is really useful NOTE for me...

1) Another question!! I know what a virtual destructor is.. I would like to know what is the use of pure virtual destructor??? Is it necessary that for virtual destructor there has to be a virtual constructor????

Thanks in advance
Mar 15 '07 #8
dmjpro
2,476 2GB
the VPTR is a pointer to the all virtual functions of that class....

the run time system will get the run time actual object type.....

then from that address the VPTR is retrieved and take the decision which function version will get called ....

m i clear .......
Mar 15 '07 #9
dmjpro
2,476 2GB
know one thing ... i started after totally detached from C++ for one year...

so right now i can't clearify the destructor .. actually i am working on J2EE

but after 10-15 days i wil be as i was before one year ......

okkkkkk... so look for another expert and have a good day......
Mar 15 '07 #10
Banfa
9,065 Expert Mod 8TB
Actually, they are functions which a derived class must define. Any derived class can override any base class's function, but it has the option of doing so. Declaring a function as virtual requires subclasses to redefine the function.
Err actually Ganon this just isn't true. I did have to look this up to be sure about it but from section 12.2.6 of "The C++ Programming Language" by B. Stroustrup
A virtual function can beused even if no class is derived from its class, and a derived class that does not need its own version of a virtual function need not provide one. When deriving a class, simply provide an appropriate function, if it is needed.
So a class is not required to redefine a function that is declared virtual in one of its parent classes, but it may if it needs to.

The big difference is that when a function is declared virtual you are guaranteed that the correct function for the object will be called regardless of the type of the reference it is called through.

As illustrated in the difference between PrintMe and PrintMsg in the program below. PrintHelloWorld is an example of a non over ridden virtual function.

Note:

If you fail to override a pure virtual function inherited from an abstract parent class then the derived class will also be abstract since it will contain a pure virtual function.

If you declare any functions virtual it is good practice to declare the destructor virtual too.

Expand|Select|Wrap|Line Numbers
  1. #include "iostream"
  2. using namespace std;
  3.  
  4. class Base
  5. {
  6. public:
  7.     virtual void PrintMe(){ cout << "Base" << endl; }
  8.     virtual void PrintHelloWorld(){ cout << "Hello World" << endl; }
  9.     void PrintMsg(){ cout << "I'm in Base" << endl; }
  10.  
  11.     Base(){};
  12.     virtual ~Base(){};
  13. };
  14.  
  15. class Derived : public Base
  16. {
  17. public:
  18.     virtual void PrintMe(){ cout << "Derived" << endl; }
  19.     void PrintMsg(){ cout << "I'm in Derived" << endl; }
  20.  
  21.     Derived(){};
  22.     virtual ~Derived(){};
  23. };
  24.  
  25. int main()
  26. {
  27.     Derived d;
  28.     Base &rb = d;
  29.  
  30.     rb.PrintMe();
  31.     rb.PrintHelloWorld();
  32.     rb.PrintMsg();
  33.  
  34.     return 0;
  35. }
  36.  
Mar 15 '07 #11
Ganon11
3,652 Expert 2GB
Err actually Ganon this just isn't true.7
Hrm. I, also, had to look this up to make sure, but you're right. I guess that was a leftover confusion from working with abstract in Java, where there was no 'virtual' option, only the equivalent of pure virtual. Sorry for any confusion caused.
Mar 15 '07 #12
vermarajeev
180 100+
Firstly thanks to dmjpro for a quick and comforting reply.

Hi Banfa,
Thanks for your satisfying reply. Now my concept is becoming more clearer.

But still this questions are to be answered..

1)I would like to know what is the use of pure virtual destructor???

2)About VPTR. dmjpro has already explained about it in the previous post but still I'm unclear and has not got a clear picture.

Could you please help me to understand above two questions.

Thanks
Mar 16 '07 #13
dmjpro
2,476 2GB
look at this code what compiler inserts silently......

Expand|Select|Wrap|Line Numbers
  1. class A
  2. {
  3.    void * VPTR = holds the address of the off all virual funations of class A
  4.    //some code
  5.    virtual void fun()
  6.    {
  7.       //Class A function fun
  8.    }
  9.    //some code
  10. };
  11.  
  12. class B : public A
  13. {
  14.    void * VPTR = holds the address of the off all virual funations of class B
  15.    //some code
  16.    virtual void fun()
  17.    {
  18.       //Class B function fun
  19.    }
  20.    //some code
  21. };
  22.  
  23. //some code .....
  24. B b;
  25. A a;
  26. A *ap = &b;
  27. ap->fun();//here now ap holds the address of class B object and the corresponding VPTR retrieved and actual adress of fun function retrieved and gets called
  28.  
  29. //similarly solved if ...... ap = &a and ap->fun();
okk .... i think now u got my point .....

welcome again...... have a good day...
Mar 16 '07 #14
vermarajeev
180 100+
Thanks.... Now it gives a clear picture.

Thanks again
Mar 16 '07 #15

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...
5
by: Ryan Faulkner | last post by:
Hi, Im having a few problems with virtual functions (Im using the Visual C++ environment by the way). I have a base class with three virtual functions and a derived class with a single new...
18
by: nenad | last post by:
Wouldn't it be nice if we could do something like this: class Funky{ public: auto virtual void doStuff(){ // dostuff } };
19
by: qazmlp | last post by:
class base { // other members public: virtual ~base() { } virtual void virtualMethod1()=0 ; virtual void virtualMethod2()=0 ; virtual void virtualMethod3()=0 ;
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...
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...
10
by: John Goche | last post by:
Hello, page 202 of Symbian OS Explained by Jo Stichbury states "All virtual functions, public, protected or private, should be exported" then page 203 states "In the rare cases where a...
5
by: Dilip | last post by:
In a polymorphic hierarchy is it common practice to have public virtual functions in the base class with a default empty implementation and let the derived classes decide whether they want to...
14
by: v4vijayakumar | last post by:
Why we need "virtual private member functions"? Why it is not an (compile time) error?
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.