Using virtual, polymorphism

Started by
3 comments, last by Drakkcon 19 years, 11 months ago
Alright, another nüb question to fill the chasms in Drakkcon''s amnesiac (sp?) brain! I understand polymorphism. Well, okay - I understand that if a class inherits a function from another class you must use the virtual keyword for the child class or you get wrong answers (I''m not interested in theory). But is it neccisary for for me to use virtual for the parent class? Why is this even an issue anyway!? I told the compiler:

MyClass foo
foo.docrap();
foo.object.docrap();
 
Why isn''t it totally obvious that I''m referring to object? Would this be so hard to implement? Note to C# fanatics: I''m aware that your language does not likely have this problem. The true general first seeks victory, then seeks battle - Sun Tzu
Advertisement
What exactly are you trying to acheive here? Call the base class implementation? What is foo deriving from?
The following example might help you:

class foo {public:    virtual void docrap() {printf("foo");}    virtual void docrap2() {printf("foo");}};class object : public foo {public:    virtual void docrap() {printf("object");}    virtual void docrap2() {foo::docrap2();}}foo *p = new object();foo o = *p;  // This is an illegal statementp->docrap();    // Will print "object", even though p is a pointer to foop->docrap2();   // Will print "foo", because object''s implementation calls that of the base class 


There is some good info on virtual members here:
http://www.cplusplus.com/doc/tutorial/tut4-4.html

- Xavier
I am not sure whether you truely understand what polymorphism is. However, one thing that I am sure is that you don''t understand what the ''virtual'' keyword is used for. Virtual is only used for the upper class (parent), generally not on child (but you could though).

Anyway, you should read some more on virtual to get a better understanding. As for your code, I am not sure what you''re trying to show there.
This form of polymorphism allows the code to call different functions based on the dynamic (runtime) type of an object. The way this is done is by declaring the function as virtual in the parent class, so that the compiler knows that whenever this (parent) function is called, it needs to figure out the runtime object''s actual, dynamic type. Note that unless you have a base class pointer, it is known at compile time what the exact type of the object is, so the whole thing becomes moot. It only kicks in when you have a derived object pointed to by a base class pointer.
And that solves the problem. Thank you. True, I don't understand. When a book devotes a giant chapter, so boring that my eyes glaze over, to a problem that can be solved with one keyword; i tend to lose focus. thanks for the fix though.

EDIT: @ johnson 5001


[edited by - Drakkcon on May 6, 2004 11:02:33 PM]

This topic is closed to new replies.

Advertisement