Function Overloading vs Function Overriding in C
Function Overloading vs Function Overriding in C
Function Overloading provides multiple definitions of the function by changing signature i.e.
changing number of parameters, change datatype of parameters, return type doesn’t play
any role.
CPP
// Function Overloading
#include <iostream>
// overloaded functions
void test(int);
void test(float);
int main()
int a = 5;
float b = 5.5;
// Overloaded functions
// number of parameters
test(a);
test(b);
test(a, b);
return 0;
// Method 1
// Method 2
// Method 3
Output
Integer number: 5
It is the redefinition of base class function in its derived class with same signature i.e. return
type and parameters.
Example:
Class a
public:
};
Class b:public a
public:
};
CPP
// Function Overriding
#include<iostream>
class BaseClass
public:
" of BaseClass";
void Show()
"of BaseClass";
};
public:
void Display()
" of DerivedClass";
}
};
// Driver code
int main()
DerivedClass dr;
bs.Display();
dr.Show();
Output
Overloading is used when the same function Overriding is needed when derived class
has to behave differently depending upon function has to do some different job
parameters passed to them. than the base class function.
A function has the ability to load multiple A function can be overridden only a single
times. time.
Classes in C++ are a key feature of the language, used for creating objects with specific
attributes and behaviors. They encapsulate data and functions into a single entity, promoting
an object-oriented approach to programming. Here's a simple explanation and example for
better understanding:
1. **Class Declaration:** This is where you define a class and its members.
2. **Class Members:** These include variables (called member variables or attributes) and
functions (called member functions or methods).
```cpp
#include <iostream>
// Class Declaration
class Car {
// Member Variables
string brand;
string model;
int year;
// Member Function
void displayInfo() {
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.year = 2021;
myCar.displayInfo();
return 0;
```
- **Access Specifiers:** Define the access level/visibility of class members. The common
ones are:
- `protected`: Members cannot be accessed from outside the class, but they can be
accessed in inherited classes.
By using classes, you can model real-world entities, make your code more modular, and
easier to manage and understand. Would you like to know more about advanced concepts
like inheritance or polymorphism in C++?