|
-
Jan 13th, 2001, 12:14 AM
#1
Thread Starter
Lively Member
can somebody explain to me what this keyword means?
i see it in alot of source, but i have no idea what the point behind it is:
virtual int GetSomeNumber(){ return m_Number;};
what is the diffrence of just using "int" and throwing a "virtual" infront of it?
-
Jan 13th, 2001, 06:31 AM
#2
Frenzied Member
A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.
Code:
Example
class WageEmployee
{
public:
virtual float computePay();
};
class SalesPerson : public WageEmployee
{
public:
float computePay();
};
WageEmployee aWorker;
SalesPerson aSeller;
WageEmployee *wagePtr;
wagePtr = &aWorker;
wagePtr->computePay(); // call WageEmployee::computePay
wagePtr = &aSeller;
wagePtr->computePay(); // call SalesPerson::computePay
The virtual keyword is needed only in the base class's declaration of the function; any subsequent declarations in derived classes are virtual by default.
A derived class's version of a virtual function must have the same parameter list and return type as those of the base class. If these are different, the function is not considered a redefinition of the virtual function. A redefined virtual function cannot differ from the original only by return type.
-
Jan 13th, 2001, 07:32 AM
#3
Monday Morning Lunatic
Grrrr...line breaks
You can also have pure virtual functions. They differ from virtual functions in that they must be redefined. This causes their class to become an abstract class. For example:
Code:
class Shape {
virtual void Draw() = 0;
};
class Square : public Shape {
void Draw() { }
};
class Circle : public Shape {
void Draw() { }
};
This means that you cannot do this:
...or you'll get a "cannot instantiate abstract class" error from the compiler.
Pure virtual functions don't add any other significant functionality other than base class protection.
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
-
Jan 13th, 2001, 02:45 PM
#4
Thread Starter
Lively Member
Thanks!
ok i get it now.. thanks alot =)
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
|