|
-
May 2nd, 2001, 04:10 PM
#1
Thread Starter
Member
question regarding virtual methods
I understand what a virtual function is:
Code:
class Base
{
public:
virtual int DoSomething();
int DoSomethingElse();
};
class Derived : public Base
{
public:
int DoSomething();
int DoSomethingElse();
};
int main(void)
{
Derived* d = new Derived;
Base* b = d;
d->DoSomething(); // Calls Derived::DoSomething()
b->DoSomething(); // Calls Derived::DoSomething()
d->DoSomethingElse(); // Calls Derived::DoSomethingElse()
b->DoSomethingElse(); // Calls Base::DoSomethingElse()
d->Base::DoSomethingElse(); // Calls Base::DoSomethingElse()
delete d;
return 0;
}
My question is: Why wouldn't you make all functions virtual?
I am just learning C++ and this concept doesn't make alot of sense right now. Also, does a virtual function have to be overriden by a derived class???
Thanks for any help
-
May 2nd, 2001, 05:38 PM
#2
Monday Morning Lunatic
Sometimes you want to call the function related to that pointer's type, or you may want to specifically call a base class function on a derived class. That's why there's a choice.
Virtual functions don't have to be overridden unless they're Pure Virtual Functions, the presence of which create an abstract class that can't be used, only derived from:
Code:
class Base {
public:
int MyFunction(int x) = 0; // Pure virtual
};
I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
-- Linus Torvalds
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|