Inheritance

Hi hackers,
What is meant by naming a function virtual, I read it means that the function is dynamically binded. Could you tell me what this means or send me a link about virtual functions. Usually I get good info when asking.

thank you,
Last edited on
I was able to dig up that it signals the compiler that you don't want static linkage for the function. What you do want is the selection of the function to be called at any given point in the program based on the kind of object for which it was called. I guess it gets more complicated with the use of a pointer, it means that the version of the function in the object the pointer actually points at during execution will be called. Anything that you could add would be helpful.

thanks,
Last edited on
virtual functions call a function based on the ACTUAL type of the object, whereas nonvirtual functions call a function based on the APPARENT type of the object.

Another way to say it is that the type of the object for virtual functions is determined at runtime, whereas the type of the object for nonvirtuals is determined at compile time.

Here's an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Parent
{
public:
  virtual void virt()
  {
    cout << "Parent::virt\n";
  }
  void notvirt()
  {
    cout << "Parent::notvirt\n";
  }
};

class Child : public Parent
{
public:
  virtual void virt()
  {
    cout << "Child::virt\n";
  }
  void notvirt()
  {
    cout << "Child::notvirt\n";
  }
};

//====================

int main()
{
  Parent parentobj;  // a Parent Object ("actually" a Parent)
  Child childobj;   // a Child Object ("actually" a Child)

  Parent* p;  // a Parent pointer -- it "appears" to point to a Parent
     // even though it could actually be pointing to something else

  //================

  p = &parentobj;  // point to the Parent object
  p->nonvirt();  // Parent::nonvirt because p is a Parent pointer
  p->virt();   // Parent::virt because p actually points to a Parent

  // vs.

  p = &childobj;  // point to the Child object
  p->nonvirt();  // Parent::nonvirt because p is a Parent pointer
  p->virt();  // Child::virt because p actually points to a Child.

  return 0;
}
thanks for your help,
I was also able to dig this up

"what the virtual keyword does is to allow a member of a derived class with the same name as one in the base class to be appropriately called from a pointer, and more precisely when the type of the pointer is a pointer to the base class but is pointing to an object of the derived class"

http://www.cplusplus.com/doc/tutorial/polymorphism.html

Last edited on
Topic archived. No new replies allowed.