티스토리 뷰

C++

Virtual Function in C++

seoca 2018. 11. 22. 13:00
Virtual Function

  • return data type must be the same.
  • It is better not to use it when calls are frequent because a program can get slow.
  • The reason for using a virtual function is the same as that of inheritance. The member function can be called as an object of the parent class.



Example code


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Fruit {
protected:
    string m_name;
public:
    Fruit(string name) : m_name(name) {} // 
    string getName() { return m_name; };
    
    virtual void speak() const { //only parents class needs virtual
        cout << m_name << " fruits are good " << endl;
    }
};
 
class Apple : public Fruit {
public
    Apple(string name) : Fruit(name) {}
    void speak() const {
        cout << m_name << " apple slices" << endl;
    }
};
 
class Banana : public Fruit {
public:
    Banana(string name) : Fruit(name) {}
    void speak() const {
        cout << m_name << " Banana smoothie" << endl;
    }
 };
 
int main() {
    Apple arr_app[] = { Apple("a1"),Apple("a2"),Apple("a3"),Apple("a4") };
    Banana arr_ba[] = { Banana("b1"),Banana("b2") };
 
    Fruit *my_fruit[] = { &arr_app[0],&arr_app[1],&arr_app[2],&arr_app[3],&arr_ba[0],&arr_ba[1] };
                        //There are two different classes, but they inherit from the same parent, 
                        //so it's OK to be in the same array.
 
    for (int i = 0; i < 6; i++)
    {
        my_fruit[i]->speak();
        //It is a pointer to the parent class, but runs as if it were a child class
    }
 
    return 0;
}
cs




Result


'C++' 카테고리의 다른 글

Vector & List in C++  (0) 2018.11.22
Friend in C++  (0) 2018.11.22
Templates (Function Template & Class Template) in C++  (0) 2018.11.10
Exception handling (Try Throw and Catch) in C++  (0) 2018.11.09
Inline function in C++  (0) 2018.11.09