How C + + handles inline virtual functions

Source: Internet
Author: User
Tags function definition

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; }
    };

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.