AD

Breaking News

Programming basics


Polymorphism:

The word Polymorphism means ‘more than one form’. In OOP polymorphism means when same entity i.e.  Function or object behaves differently in different scenarios.

Code:
class Animal {

  public:
    void animalSound() {
      cout << " Animal makes a sound ";   }
};
class Cat : public Animal {

  public:
    void animalSound() {
      cout << "Cat says: mewo mewo";  }
};
class Dog : public Animal {

  public:
    void animalSound() {
      cout << "Dog says: bow bow "; }
};

int main() {
Animal myAnimal;
 Car myCat;
  Dog myDog;
  myAnimal.
animalSound();
  myCat.
animalSound();
  myDog.
animalSound();
  return 0;

}

Inheritance:

The technique of inheriting methods and functions from one class to another class in called inheritance.

Derived class: the class that inherits attributes from another class. (Child class)

Base class: the class that is being inherited. (Parent class).

Code:


class Vehicle {

  public:
  string model = "corolla";
  void horn() {
  cout << “peen peen” ; }
};
class Car:  public Vehicle {

  public:
    string varient = "gli";
};
int main() {
 Car myCar;
 myCar.
horn();
 cout << myCar.
model + " " + myCar.varient;
  return 0;

}Encapsulation:

The process of hiding data to protect the data and behavior of the object. It is the process of hiding the data variables and methods in a single unit.

Code:  

class Example{
private:
  int num;
public:
  int getNum() const {
     return num; }
   void setNum(int num) {
     this->num = num;   }
};
 
int main(){
   Example obj;
   obj.setNum(22);
   cout<<obj.getNum()<<endl;
   return 0;
}

 

Abstraction:

Abstraction is displaying important information and hiding extra details. Abstraction means to provide essential information only to the outside world. And hiding the details and implementation methods.

Code:

class Abstraction {

private:

    int x, y;

public:

    void set(int m, int n)

    {

        x = m;

        y = n;

    }

    void display()

    {

        cout << "x = " << x << endl;

        cout << "y = " << y << endl; }

}; 

int main()

{

    Abstraction obj;

    obj.set(1,2);

    obj.display();

    return 0;

} 

No comments

Thanks you