Mobile wallpaper 1Mobile wallpaper 2Mobile wallpaper 3Mobile wallpaper 4Mobile wallpaper 5Mobile wallpaper 6
231 字
1 分钟
Overload, Override and Static

1. Difference Between Overloading and Overriding#

AspectOverloadingOverriding
DefinitionSame function name with different parameter listsRedefining a virtual function in a derived class
Inheritance required❌ No✅ Yes
ParametersMust be differentMust be the same
Return typeCan differ (with rules)Must be the same or covariant
BindingCompile-time (static binding)Run-time (dynamic binding)
Keyword needed❌ Novirtual (base), override (derived, recommended)
PolymorphismCompile-time polymorphismRun-time polymorphism

2. How to Implement Overloading and Overriding#


(A) Function Overloading (Compile-Time Polymorphism)#

class Math {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};

📌 Same function name, different parameter types.


(B) Function Overriding (Run-Time Polymorphism)#

class Base {
public:
virtual void show() {
cout << "Base show" << endl;
}
};
class Derived : public Base {
public:
void show() override {
cout << "Derived show" << endl;
}
};
Base* obj = new Derived();
obj->show(); // Output: Derived show

📌 Requires:

  • Inheritance
  • virtual function in base class
  • Same function signature

3. Purpose of Using Static Data#

A static data member belongs to the class itself, not to individual objects.


Why Use Static Data?#

  • Shared among all objects of the class
  • Maintains common state
  • Saves memory (only one copy exists)
  • Useful for counting objects
  • Represents class-level information

Example#

class Counter {
public:
static int count;
Counter() { count++; }
};
int Counter::count = 0;
Counter a, b, c;
cout << Counter::count; // Output: 3

One-Line Exam Summary#

  • Overloading: Same function name, different parameters (compile-time).
  • Overriding: Redefining a virtual function in a derived class (run-time).
  • Static data: Shared class-level data used by all objects.
Overload, Override and Static
https://mizuki.anka2.top/posts/l5-cpp-week12-lecture/overload-override-static/
作者
🐦‍🔥不死鸟Anka
发布于
2025-12-15
许可协议
MIT

部分信息可能已经过时

封面
Sample Song
Sample Artist
封面
Sample Song
Sample Artist
0:00 / 0:00