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.
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.
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.
class Parent
{
public:
virtualvoid virt()
{
cout << "Parent::virt\n";
}
void notvirt()
{
cout << "Parent::notvirt\n";
}
};
class Child : public Parent
{
public:
virtualvoid 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"