C++ Polymorphism
free template from www.brainybetty.com Contoh Kode (1) File => New Pilih C++ Source File 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (2) 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (3) Kemudian tambahkan kode sehingga tampak seperti berikut: #include <iostream> #include <string> using namespace std; 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (4) class Man{ protected: string name; short age; public: Man(string name, short age):name(name),age(age){ } virtual void showAttributes(){ }; class Artist: public Man{ 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (5) private: string alias; public: Artist(string name, short age,string alias):Man(name,age), alias(alias){ } void showAttributes(){ cout << "ARTIST " << name << endl; 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (6) }; class Lecturer: public Man{ private: string course; public: Lecturer(string name, short age,string course):Man(name,age),course(course){ } void showAttributes(){ cout << "LECTURER " << name << endl; 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Contoh Kode (7) int main(){ Artist me("Tukul",59,"Cink Cank Conk"); Lecturer u("Marshanda",17,"C++"); Man* it = &me; it->showAttributes(); it = &u; return 0; } 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Diseksi (1) [14,25] Keduanya klas Artist dan klas Lecturer didefinisikan memperluas klas yang sama, yaitu: klas Man. [11,12] Member fungsi showAttributes() di dalam klas Man dideklarasikan virtual. [21..23,31..33] Masing-masing klas Artist dan klas Lecturer meng-override member fungsi showAttributes() yang diturunkan dari klas Man. [38..41] Variabel it bertipe pointer to Man dan digunakan untuk menunjuk ke objek me yang bertipe Artist serta ke objek u yang bertipe Lecturer. Member fungsi showAttributes() yang bersesuaian akan dipanggil. 9/16/2018 free template from www.brainybetty.com
free template from www.brainybetty.com Output Tekan Ctrl+F7, lalu F7, selanjutnya Ctrl+F5 untuk me-run program 9/16/2018 free template from www.brainybetty.com