When a function is an inline and virtual function, code substitution or virtual table invocation occurs? To find out the inner and virtual functions, let's consider them separately. Typically, an inline function is expanded.
class CFoo {
private:
int val;
public:
int GetVal() { return val; }
int SetVal(int v) { return val=v; }
};
Here, if you use the following code:
CFoo x;
x.SetVal(17);
int y = x.GetVal();
The object code generated by the compiler will be the same as the following code snippet:
CFoo x;
x.val = 17;
int y = x.val;
Of course you can't do that, because Val is a private variable. The advantage of inline functions is that you can hide data without a function call, that's all.
Virtual functions have polymorphism, which means that derived classes can implement the same functions but differ in functionality. Suppose Getval is declared as a virtual function, and one has a second class CFoo2 implemented in different ways:
class CFoo2 : public CFoo {
public:
// virtual in base class too!
virtual int CFoo2::GetVal() {return someOtherVal;}
};
If Pfoo is a cfoo or CFoo2 pointer, the member function Cfoo can invoke success regardless of which class CFoo2 or pfoo->getval the Pfoo points to.
What happens if a function is both a virtual function and an inline function? Remember, there are two ways to create an inline function,
The first is to use the keyword inline in the function definition, such as:
inline CFoo::GetVal() { return val; }
The second is to write the function body in the declaration of the class, just like the cfoo2::getval in front. So if you include a virtual function body in the declaration of a class, such as:
class CFoo {
public:
virtual int GetVal() { return val; }
};