У цьому підручнику ми дізнаємося про перевизначення функцій у C ++ за допомогою прикладів.
Як ми знаємо, успадкування - це особливість ООП, яка дозволяє нам створювати похідні класи з базового класу. Похідні класи успадковують особливості базового класу.
Припустимо, однакова функція визначена як у похідному класі, так і в базовому класі. Тепер, якщо ми викликаємо цю функцію, використовуючи об'єкт похідного класу, виконується функція похідного класу.
Це відомо як перевизначення функції в C ++. Функція в похідному класі замінює функцію в базовому класі.
Приклад 1: Заміна функції C ++
// C++ program to demonstrate function overriding #include using namespace std; class Base ( public: void print() ( cout << "Base Function" << endl; ) ); class Derived : public Base ( public: void print() ( cout << "Derived Function" << endl; ) ); int main() ( Derived derived1; derived1.print(); return 0; )
Вихідні дані
Похідна функція
Тут та ж функція print()
визначається як Base
і Derived
класів.
Так що , коли ми називаємо print()
від Derived
об'єкта Derived1, то print()
від Derived
виконується шляхом перевизначення функції в Base
.

Доступ до перевизначеної функції в C ++
Для доступу до заміненої функції базового класу ми використовуємо оператор роздільної здатності ::
.
Ми також можемо отримати доступ до заміненої функції, використовуючи вказівник базового класу, щоб вказати на об'єкт похідного класу, а потім викликати функцію з цього вказівника.
Приклад 2: Перекрита функція доступу C ++ до базового класу
// C++ program to access overridden function // in main() using the scope resolution operator :: #include using namespace std; class Base ( public: void print() ( cout << "Base Function" << endl; ) ); class Derived : public Base ( public: void print() ( cout << "Derived Function" << endl; ) ); int main() ( Derived derived1, derived2; derived1.print(); // access print() function of the Base class derived2.Base::print(); return 0; )
Вихідні дані
Похідна функція Базова функція
Ось, це твердження
derived2.Base::print();
отримує доступ до print()
функції базового класу.

Приклад 3: Функція перевизначення виклику C ++ із похідного класу
// C++ program to call the overridden function // from a member function of the derived class #include using namespace std; class Base ( public: void print() ( cout << "Base Function" << endl; ) ); class Derived : public Base ( public: void print() ( cout << "Derived Function" << endl; // call overridden function Base::print(); ) ); int main() ( Derived derived1; derived1.print(); return 0; )
Вихідні дані
Похідна функція Базова функція
У цій програмі ми викликали перевизначену функцію всередині самого Derived
класу.
class Derived : public Base ( public: void print() ( cout << "Derived Function" << endl; Base::print(); ) );
Зверніть увагу на код Base::print();
, який викликає перевизначену функцію всередині Derived
класу.

Приклад 4: Функція перевизначення виклику C ++ за допомогою покажчика
// C++ program to access overridden function using pointer // of Base type that points to an object of Derived class #include using namespace std; class Base ( public: void print() ( cout << "Base Function" << endl; ) ); class Derived : public Base ( public: void print() ( cout << "Derived Function"
Output
Base Function
In this program, we have created a pointer of
Base
type named ptr. This pointer points to the Derived
object derived1.
// pointer of Base type that points to derived1 Base* ptr = &derived1;
When we call the
print()
function using ptr, it calls the overridden function from Base
.
// call function of Base class using ptr ptr->print();
This is because even though ptr points to a
Derived
object, it is actually of Base
type. So, it calls the member function of Base
.
In order to override the
Base
function instead of accessing it, we need to use virtual functions in the Base
class.