ใน C ++ เราสามารถใช้เทคนิคการโอเวอร์โหลดฟังก์ชันได้ แต่ถ้าคลาสฐานบางคลาสมีเมธอดเดียวในรูปแบบโอเวอร์โหลด (ลายเซ็นฟังก์ชันต่างกันที่มีชื่อเดียวกัน) และคลาสที่ได้รับมากำหนดฟังก์ชันที่มีอยู่ภายในฐานใหม่ เวอร์ชันโอเวอร์โหลดทั้งหมดของฟังก์ชันนั้นจะถูกซ่อนจาก คลาสที่ได้รับ
เรามาดูตัวอย่างกันเพื่อให้ได้แนวคิดที่ชัดเจน
ตัวอย่าง
#include <iostream>
using namespace std;
class MyBaseClass {
public:
void my_function() {
cout << "This is my_function. This is taking no arguments" << endl;
}
void my_function(int x) {
cout << "This is my_function. This is taking one argument x" << endl;
}
};
class MyDerivedClass : public MyBaseClass {
public:
void my_function() {
cout << "This is my_function. From derived class, This is taking no arguments" << endl;
}
};
main() {
MyDerivedClass ob;
ob.my_function(10);
} ผลลัพธ์
[Error] no matching function for call to 'MyDerivedClass::my_function(int)' [Note] candidate is: [Note] void MyDerivedClass::my_function() [Note] candidate expects 0 arguments, 1 provided