Method Overriding

public
yeskendir.sultanov Apr 02, 2024 Never 176
Clone
C++ derived.cpp 24 lines (20 loc) | 398 Bytes
This code demonstrates function overriding in C++. In this code, there are two classes, `Base` and `Derived`. The `Base` class has a function named `print()` that prints "Base Function", while the `Derived` class inherits from the `Base` class and overrides the `print()` function to print "Derived Function" instead. Inside the `main` function, an object of the `Derived` class is created (`Derived derived1`) and its `print()` function is called. Since the `Derived` class overrides the `print()` function, the output of this program will be: ``` Derived Function ```
1
// C++ program to demonstrate function overriding
2
3
#include <iostream>
4
using namespace std;
5
6
class Base {
7
public:
8
void print() {
9
cout << "Base Function" << endl;
10
}
11
};
12
13
class Derived : public Base {
14
public:
15
void print() {
16
cout << "Derived Function" << endl;
17
}
18
};
19
20
int main() {
21
Derived derived1;
22
derived1.print();
23
return 0;
24
}