Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
12 views2 pages

Polymorphism Assignment

Uploaded by

joan.ofeimun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Polymorphism Assignment

Uploaded by

joan.ofeimun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

OFEIMUN JOAN

AUL/CMP/23/033

CMP 200L

CSC 221 ASSIGNMENT.

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP). The


word 'polymorphism' means 'many forms.' In programming, polymorphism allows
functions or objects to behave in different ways based on their context or data types.

In C++, polymorphism enables a single function name or operator to act differently on


different classes or data. It helps to write more flexible and reusable code.

Types of Polymorphism
There are two main types of polymorphism in C++:

1. Compile-Time Polymorphism (Static Polymorphism)


This type of polymorphism is resolved at compile time. It is commonly achieved using:
- Function Overloading: Same function name with different parameters.
- Operator Overloading: Redefining operators to work with user-defined data types.

E.g.:

class Display {
public:
void show(int x) {
cout << "Integer: " << x << endl;
}
void show(string str) {
cout << "String: " << str << endl;
}
};

int main() {
Display d;
d.show(10);
d.show("Anchor University");
return 0;
};

2. Runtime Polymorphism (Dynamic Polymorphism)


This type is resolved during program execution (runtime). It is achieved using inheritance
and virtual functions. A base class defines a virtual function that can be overridden by
derived classes. A base class pointer or reference is then used to call the derived class
version of the function.

E.public:
virtual void speak() {
cout << "Animal speaks" << endl;
}
};

class Dog : public Animal {


public:
void speak() override {
cout << "Dog barks" << endl;
}
};

int main() {
Animal* a;
Dog d;
a = &d;
a->speak();
return 0;
};

Conclusion
Polymorphism improves code flexibility and reusability. With compile-time polymorphism,
functions behave differently based on input types. With runtime polymorphism, behavior
depends on the object being referred to, allowing for dynamic behavior in programs.

You might also like