# Polymorphism and Inheritance

## Polymorphism

&#x20;    Polymorphism หมายถึง การมีหลายรูปแบบ หรือก็คือ ใน 1 กระบวนการหรือการกระทำสามารถแสดงผลลัพธ์หรือแสดงผลการกระทำได้มากกว่าหนึ่งรูปแบบ แบ่งออกเป็น 2 ประเภท

### &#x20;1. Function Overloading

&#x20;    การใช้ชื่อฟังก์ชันเหมือนกัน แต่มีความสามารถหรือคุณลักษณะที่แตกต่างกัน หมายความว่า ฟังก์ชันสามารถเปลี่ยนจำนวการรับพารามิเตอร์หรือเปลี่ยนประเภทตัวแปรของพารามิเตอร์

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_1.cpp
#include <iostream>
using namespace std;

class function_overlasding 
{ 
    public: 
      
    // function with 1 int parameter 
    int func(int x) { 
        return x + 5; 
    } 
      
    // function with same name but 1 double parameter 
    void func(double x) { 
        cout << "value of x is " << x << endl; 
    } 
      
    // function with same name and 2 int parameters 
    void func(int x, double y) { 
        cout << "value of x and y is " << x << ", " << y << endl; 
    } 
}; 
  
int main() { 
      
    function_overlasding obj1; 
      
    // Which function is called will depend on the parameters passed 
    // The first 'func' is called  
    int a = obj1.func(7);
    cout << a  << endl; 
      
    // The second 'func' is called 
    obj1.func(9.132); 
      
    // The third 'func' is called 
    obj1.func(85,9.132); 
    return 0; 
}  
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```cpp
12
value of x is 9.132
value of x and y is 85, 9.132
```

{% endtab %}
{% endtabs %}

&#x20;    จากตัวอย่างจะเห็นได้ว่าฟังก์ชันที่ชื่อ func ทำหน้าที่แตกต่างกันใน 3 สถานการณ์ (การรับพารามิเตอร์) ที่แตกต่างกัน ซึ่งเป็นคุณสมบัติของ  Polymorphism

&#x20;

### &#x20;    2. Operator Overloading

&#x20;    operator ที่ทำงานได้หลายแบบ ในหลักการเชิงวัตถุจะช่วยให้สามารถเรียกใช้เครื่องหมายเช่น +, -, \*, / แทนการเรียกใช้เมดธอดหรือฟังก์ชันของ object&#x20;

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_2.cpp
#include <iostream>
using namespace std;
   
class Complex { 
    private: 
        int real, imag; 
    public: 
        // first section code
        Complex(int r = 0, int i =0) {
            real = r;   imag = i;
        } 
        
        // second section code
        // This is automatically called when '+' is used with 
        // between two Complex objects 
        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; // An example call to "operator+" 
    c3.print(); 
} 
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
12 + i9
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
ตัวอย่างให้ศึกษาเพิ่มเติม :: [การ overload operator ใน C++](https://preecha11th.wordpress.com/2011/12/23/%e0%b8%81%e0%b8%b2%e0%b8%a3-overload-operator-%e0%b9%83%e0%b8%99-c/)
{% endhint %}

## **Inheritance**

&#x20;    Inheritance คือ การสืบทอดความสามารถของ class ในการรับคุณสมบัติและลักษณะจาก class อื่น&#x20;

**ศัพย์ที่ควรรู้** ::

&#x20;  Sub Class คือ คลาสที่สืบทอดคุณสมบัติจากคลาสอื่น เรียกว่า คลาสที่ได้รับ (Derived Class)

&#x20;  Super Class คือ คลาสที่มีคุณสมบัติสืบทอดหรือที่รู้จักกันว่าเป็นคลาสตั้งต้น  (Base Class)

![](https://paper-attachments.dropbox.com/s_FD9EBFBBCB85F11ADE83B637E93E9D49FBF66A3A050C05F009AAAAD62A441DB4_1610596774666_Screenshot+from+2021-01-14+10-59-22.png)

&#x20;    จากภาพ หมายความว่า Animal class ถือว่าเป็น Base Class ส่วน dog class, Cat class และ Cow class จะเป็นเพียง Derived Class ของ Animal class ซึ่งการสืบทอดความสามารถจะมีหลายแบบ แต่ในหัวข้อนี้จะกล่าวถึงเพียงแค่ 3 แบบ คือ การสืบทอดทางเดียว (Single Inheritance) การสืบทอดหลายรายการ (Multiple Inheritance) และการสืบทอดหลายนะดับ (Multilevel Inheritance)&#x20;

### **1. Single Inheritance**

&#x20;    การสืบทอดทางเดียว หมายความว่า 1 Derived Class สามารถรับการสืบทอดได้ 1 Base Class เท่านั้น

![](/files/-MSXBEtpXLEqYonrDPv8)

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_3.cpp
#include <iostream>
#include <string>
using namespace std;

// Base class
class Vehicle {
  public: 
    string brand = "Ford";
    void honk() {
      cout << "Tuut, tuut! \n" ;
    }
};

// Derived class
class Car: public Vehicle {
  public: 
    string model = "Mustang";
};

int main() {
  Car myCar;
  myCar.honk();
  cout << myCar.brand + " " + myCar.model << endl;
  return 0;
}
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
Tuut, tuut! 
Ford Mustang
```

{% endtab %}
{% endtabs %}

### **2. Multiple Inheritance**

&#x20;    การสืบทอดหลายหลายการ หมายความว่าใน 1 Derived Class สามารถสืบทอดได้มากว่า 1 Base Class

![](/files/-MSWq6i726oZ7ajQjOqr)

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_4.cpp
#include <iostream> 
using namespace std; 
  
// first base class 
class Vehicle { 
  public: 
    Vehicle() 
    { 
      cout << "This is a Vehicle" << endl; 
    } 
}; 
  
// second base class 
class FourWheeler { 
  public: 
    FourWheeler() 
    { 
      cout << "This is a 4 wheeler Vehicle" << endl; 
    } 
}; 
  
// sub class derived from two base classes 
class Car: public Vehicle, public FourWheeler { 
  
}; 
  
// main function 
int main() 
{    
    // creating object of sub class will 
    // invoke the constructor of base classes 
    Car obj; 
    return 0; 
} 
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
This is a Vehicle
This is a 4 wheeler Vehicle
```

{% endtab %}
{% endtabs %}

### 3. Multilevel Inheritance

&#x20;    การสืบทอดหลายนะดับ หมายความว่า Derived Class สามารถรับการสืบทอด Base Class ที่สืบทอดกันมาก่อนได้

![](/files/-MSWqAJMesPi9no-z7og)

&#x20;    จากภาพจะเห็นได้ว่า Class C จะเป็น Base Class หลักของการสืบทอด ส่วน Class B จะเป็นทั้ง Derived Class ของ Class C และเป็น Base Class ของ Class A อีกทีหนึ่ง ทำให้ Class A ที่เป็น Derived Class สุดท้ายสามารถสืบทอดได้ทั้งคุณสมบัติของ Class B และ Class C

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_5.cpp
#include <iostream> 
using namespace std; 
  
// base class 
class Vehicle  
{ 
  public: 
    Vehicle() 
    { 
      cout << "This is a Vehicle" << endl; 
    } 
}; 
class fourWheeler: public Vehicle 
{  public: 
    fourWheeler() 
    { 
      cout<<"Objects with 4 wheels are vehicles"<<endl; 
    } 
}; 
// sub class derived from two base classes 
class Car: public fourWheeler{ 
   public: 
     Car() 
     { 
       cout<<"Car has 4 Wheels"<<endl; 
     } 
}; 
  
// main function 
int main() 
{    
    //creating object of sub class will 
    //invoke the constructor of base classes 
    Car obj; 
    return 0; 
} 
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
ตัวอย่างให้ศึกษาเพิ่มเติม :: [Inheritance in C++](https://www.geeksforgeeks.org/inheritance-in-c/)
{% endhint %}

####

### **Access Specifiers for Inheritance**

&#x20;    อย่างที่ทราบกันว่า Access Specifiers จะมีทั้งหมด 3 แบบ คือ public, private และสุดท้ายคือ protected ที่จะกล่าวถึงในหัวข้อนี้ ซึ่ง **protected จะเป็นการอนุญาติการเข้าถึงข้อมูลเฉพาะ class ที่เป็น Derived class เท่านั้น**&#x20;

&#x20;    ถึงแม้ว่าใน Inheritance จะเป็นการสืบทอดความสามารถของ class แต่**ไม่สามารถสืบทอดความสามารถที่ถูกจำกัดการเข้าถึงแบบ private ที่อยู่ใน Base class** หมายความว่า ไม่สามารถสร้างเมดธอดหรือฟังก์ชันที่จะเข้าถึงข้อมูลที่เป็น private ของ Base class เนื่องจากเมดธอดหรือฟังก์ชันที่สร้างอยู่นอก class ที่มีข้อมูลที่ถูกกำหนดเป็น private&#x20;

{% tabs %}
{% tab title="Example code <using protected>" %}

```cpp
// oop_p3_6.cpp
#include <iostream>
using namespace std;

// Base class
class Employee  {
  protected:  // Protected access specifier
    int salary;
};

// Derived class
class Programmer: public Employee {
  public:
    int bonus;
    void setSalary(int s) {
      salary = s;
    }
    int getSalary() {
      return salary;
    }
};

int main() {
  Programmer myObj;
  myObj.setSalary(50000);
  myObj.bonus = 15000;
  cout << "Salary: " << myObj.getSalary() << "\n";
  cout << "Bonus: " << myObj.bonus << "\n";
  return 0;
}
```

{% endtab %}

{% tab title="Example code <using private>" %}

```cpp
// oop_p3_7.cpp
#include <iostream>
using namespace std;

// Base class
class Employee  {
  private:  // Private access specifier
    int salary;
  public:
    void set(int c){
      salary = c;
    }
    int get(){
      return salary;
    }
    
};

// Derived class
class Programmer: public Employee {
  public:
    int bonus;
    void setSalary(int s) {
      set(s);
    }
    int getSalary() {
        int ss = get();
      return ss;
    }
};

int main() {
  Programmer myObj;
  myObj.setSalary(50000);
  myObj.bonus = 15000;
  cout << "Salary: " << myObj.getSalary() << "\n";
  cout << "Bonus: " << myObj.bonus << "\n";
  return 0;
}

```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
Salary: 50000
Bonus: 15000
```

{% endtab %}
{% endtabs %}

แหล่งอ้างอิง ::

* <https://www.geeksforgeeks.org/polymorphism-in-c/?ref=lbp>
* <https://www.geeksforgeeks.org/operator-overloading-c/>
* <https://www.w3schools.com/cpp/cpp_inheritance_access.asp>

{% hint style="success" %}
**คำถาม**  สามารถนำ Polymorphism มาใช้กับ Inheritance ได้หรือไม่

**คำตอบ** สามารถทำได้
{% endhint %}

{% tabs %}
{% tab title="Example code C++" %}

```cpp
// oop_p3_8.cpp
#include <iostream> 
using namespace std; 

// Base class
class Animal {
  public:
    void animalSound() {
    cout << "The animal makes a sound \n" ;
  }
};

// Derived class
class Pig : public Animal {
  public:
    void animalSound() {
    cout << "The pig says: wee wee \n" ;
   }
};

// Derived class
class Dog : public Animal {
  public:
    void animalSound() {
    cout << "The dog says: bow wow \n" ;
  }
};

int main() {
  Animal myAnimal;
  Pig myPig;
  Dog myDog;

  myAnimal.animalSound();
  myPig.animalSound();
  myDog.animalSound();
  return 0;
}

```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Output" %}

```
The animal makes a sound 
The pig says: wee wee 
The dog says: bow wow 
```

{% endtab %}
{% endtabs %}

&#x20;    จากตัวอย่างจะเห็นได้ว่าสามารถใช้ชื่อฟังก์ชันหรือเมดธอดซ้ำกันได้ตามหลักการของ Polymorphism แต่จะการที่จะแสดงผลลัพธ์ที่แตกต่างกันต้องให้ object ประกาศเรียกใช้ class เพื่อเข้าถึงฟังก์ชันหรือเมดธอดที่มีผลลัพธ์ตามที่ต้องการ


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aic-eec.com/c-c++-for-embedded-programming/object-oriented-programming-oop-in-c++/encapsulation-and-inheritance.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
