Phần 1
1. What Problem Does It Solve?
override helps the compiler check that a function in a child class really replaces a virtual function from the parent class.
It catches mistakes such as:
Wrong function name
Wrong parameter type
Missing
const
Phần 2
2. Minimal Syntax
class Animal {
public:
virtual void talk();
};
class Cat : public Animal {
public:
void talk() override;
};Remember:
Parent class: virtual
Child class: overridePhần 3
3. Simple Example
class Animal {
public:
virtual void talk() {
cout << "Animal sound";
}
};
class Cat : public Animal {
public:
void talk() override {
cout << "Meow";
}
};When an Animal pointer points to a Cat object:
Cat cat;
Animal* p = &cat;
p->talk();Result:
MeowPhần 4
4. Why Is override Useful?
Suppose the programmer writes the wrong function name:
void taak();taak() does not replace talk().
With:
void taak() override;the compiler reports an error immediately.
Phần 5
5. Common Mistake: Missing const
These two functions are different:
void talk() const;
void talk();Correct code:
class Animal {
public:
virtual void talk() const;
};
class Cat : public Animal {
public:
void talk() const override;
};Phần 6
6. Important Rules
The parent function must be
virtual.Write
overridein the child class.The function names must match.
The parameters must match.
constmust also match.Use
overridewhenever a child class replaces a virtual function.
Phần 7
7. Easy Mental Model
virtual = allows replacing
override = checks replacingoverride means:
Compiler, check that this child function really replaces a parent virtual function.
Mã mẫu hoàn chỉnh
cpp11/16_override/main.cpp
#include <iostream>
using namespace std;
class Animal {
public:
virtual void talk() {
cout << "Animal\n";
}
};
class Cat : public Animal {
public:
void talk() override {
cout << "Meow\n";
}
};
int main() {
Cat cat;
Animal* p = &cat;
p->talk();
}Tự kiểm tra · không chấm điểm
Bạn đã hiểu những điểm nào?
Bài này chưa có danh sách tự kiểm tra trong nguồn.