Home >Backend Development >C++ >Similarities and differences between C++ inline functions and virtual functions
Inline functions embed the function body into the call point, which improves performance and code volume, but has lower readability; virtual functions call functions overridden by subclasses through polymorphism, improving flexibility, but have higher runtime overhead. .
Inline functions
Inline functions are compiled The compiler embeds the function body into the call site when it is called, rather than the function that performs the function call process.
Advantages:
Disadvantages:
Syntax:
inline int sum(int a, int b) { return a + b; }
Virtual function
Virtual function is a function that achieves polymorphism through the inheritance mechanism . When a virtual function on a parent class object is called, the actual function called is determined by the object's dynamic type.
Advantages:
Disadvantages:
virtual
and override
keywords are required. Grammar:
class Base { public: virtual void print() { std::cout << "Base" << std::endl; } }; class Derived : public Base { public: virtual void print() override { std::cout << "Derived" << std::endl; } };
Comparison of similarities and differences:
Features | Inline function | Virtual function |
---|---|---|
Calling mechanism | Function body embedding | Indirect call |
Performance | Higher | Lower |
Code size | Smaller | Bigger |
Readability | Lower | Higher |
Polymorphism | Not supported | Supported |
##Actual case:
You can use inline functions to implement simple mathematical operations, such as summation:inline int sum(int a, int b) { return a + b; } int main() { std::cout << sum(1, 2) << std::endl; // 输出:3 }You can use virtual functions to implement the graphics drawing interface:
class Shape { public: virtual void draw() = 0; }; class Circle : public Shape { public: virtual void draw() override { std::cout << "Drawing a circle" << std::endl; } }; int main() { Shape* shape = new Circle(); shape->draw(); // 输出:Drawing a circle }
The above is the detailed content of Similarities and differences between C++ inline functions and virtual functions. For more information, please follow other related articles on the PHP Chinese website!