Click to See Complete Forum and Search --> : "Virtual" key word
ExciteMouse
Jan 12th, 2001, 11:14 PM
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?
Vlatko
Jan 13th, 2001, 05:31 AM
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.
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.
parksie
Jan 13th, 2001, 06:32 AM
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:
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:
Shape x;
...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.
ExciteMouse
Jan 13th, 2001, 01:45 PM
ok i get it now.. thanks alot =)
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.