Polymorphism in C
Polymorphism in C
Function Overloading
Operator Overloading
You are also aware of inheritance in C++ very well. Therefore, we will
now implement the concept of function overloading with parent and
derived classes in C++.
#include <iostream>
class DotNetTricks {
public:
void print(int x) {
cout << "DotNetTricks was established in " << x << endl;
};
public:
cout << "ScholarHat was founded by the DotNetTricks founder, " <<
message << endl;
};
int main() {
DotNetTricks obj1;
ScholarHat obj2;
obj1.print(2015);
return 0;
}
The print() function with different parameter types is declared in
both the classes, DotNetTricks and ScholarHat.
The object obj1 of the parent class, DotNetTricks calls the print()
function of the parent class with an int argument.
The object obj2 of the child class, ScholarHat calls the overloaded
print() function in the derived class with a string argument.
Hence, we can say that the child class, ScholarHat has overloaded
the print() function of the parent class, DotNetTricks.
Output
DotNetTricks was established in 2015
#include <iostream>
#include <string>
class MyString {
public:
// Parameterized Constructor
strcpy(this->s1, str1);
strcpy(this->s2, str2);
};
int main()
// Declaring and initializing the class with the above two strings
+overload;
return 0;
Output
Welcome to ScholarHat
Function Overriding
Virtual Functions
#include <iostream>
using namespace std;
class DotNetTricks {
public:
void print() {
cout << "Welcome to DotNetTricks" << endl;
}
};
int main() {
ScholarHat obj1;
In the above code, the base class Scholarhat overrides the print()
function of the parent class, DotNetTricks. When you create an object
of ScholarHat and call its print() function, it executes the version of the
function defined in the ScholarHat class.
Output
Welcome to ScholarHat
We can even access the overridden function of the base class using the
scope resolution operator :: and the pointer of the base class.
#include <iostream>
class DotNetTricks {
public:
};
public:
void print() {
};
int main() {
ScholarHat sobj1;
ptr->print();
return 0;
Output
Welcome to ScholarHat
Difference between Runtime and Compile time
polymorphism