POLYMORPHISM
It means single things existing in multiple forms.
Real life example: A boy can be someone's brother or son or father or husband.
\*Function Overloading*
Function name same, argument lists are different.
CODE:
class A
public:
void sum (int a, int b){
cout << a+b;
}
void sum (int a, int b, intc){
cout << a+b+c;
}
};
int main ()
A obj;
obj. sum (10,20);
obj.sum (10,20,30);
return 0;
}
\*OPERATOR Overloading*
SYNTAX:
return_type operator<op>(argument list)
CODE:
class complex{
private:
int real, imag;
public:
complex (int r= 0, int i=0){
real = r;
imag=i;
}
complex operator + (Complex const & obj)
{
complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print(){
cout << real <<< "+i" << imag <<endl;
}
};
int main{
complex c1 (10,5), c2 (2,4);
complex c3=c1+c2;
c3.print();
return 0;
}
\*VIRTUAL FUNCTION*
It is a member function that is declared within a base class and is redefined by a derived class.
When we refer to a derived class object using a pointer or reference to the base class, we can virtual function for that object and execute the derived class.
CODE:
class A{
public:
virtual void display(){
cout << "base endl;
}
void show(){
cout<<"base"<<endl;
}
};
class B : public A
public:
void display(){
cout << "basel" << endl;
}
void show(){
cout << "base2"<<endl;
}
};
int main(){
A*bptr;
B d;
bptr=&d;
bptr->display();
bptr->show();
return 0;
}
ABSTRACTION
It means implementation hiding. It increases the reusability, avoid duplication.
Real life example: With a laptop we can do many things like play games, movies, etc. It does not show the inside process of how its doing the things.
CODE:
#include <iostream>
using namespace std;
class Sum
{
private: int x, y, z; // private variables
public:
void add()
{
cout<<"Enter two numbers: ";
cin>>x>>y;
z= x+y;
cout<<"Sum of two number is: "<<z<<endl;
}
};
int main()
{
Sum sm;
sm.add();
return 0;
}
ENCAPSULATION
It means wrapping up of data member and function(data hiding).
Real life example: Take a capsule, it has two parts one is solid part and second is powder particles i.e one is data member which having some properties ,states and other part is function having methods , behaviour.
WHY?
->Data hiding-security increases
->code reusability
->unit testing
CODE:
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person(string name, int age) {
this->name = name;
this->age = age;
}
void setName(string name) {
this->name = name;
}
string getName() {
return name;
}
void setAge(int age) {
this->age = age;
}
int getAge() {
return age;
}
};
int main() {
Person person("John Doe", 30);
cout << "Name: " << person.getName() << endl;
cout << "Age: " << person.getAge() << endl;
person.setName("Jane Doe");
person.setAge(32);
cout << "Name: " << person.getName() << endl;
cout << "Age: " << person.getAge() << endl;
return 0;
}