Class and Object Introduction Specifying a Class Defining Member Function A C++ Program with Class Nesting of Member Functions Private Member Functions Memory Allocation for Objects Konversi program prosedural ke OOP
CLASSES & OBJECTS SPECIFYING A CLASS class class_name { private: variable_declarations; function_declarations; public: variable_declarations; function_declarations; } Keywords private and public known as visibility labels. private can be accessed only from within the class. Data member/ Variable is commonly private. public can be accessed from outside the class. Member function is commonly public.
Class Private Area Public Area Data/ Variabel Function/ Method Data/ Variabel Function/ Method No Entry ! Entry Allowed
#include class set { private:int m, n; int largest(void) { if (m >= n)return( m ); elsereturn( n ); }; public: void input(void) { cout << "input values of m and n : " << "\n"; cin >> m >> n; }; void display(void); //declaration only }; void set :: display (void)// outside class definition { cout << "Largest value = " << largest( ) << "\n"; }//call private main( ) { set A;//creating an object A from class set A.input( ); //calling public member function A.display( ); //calling public member function }
Memory Allocation of Objects Member Function 1 Member Function 2 Object 1 Member Variabel Object 2 Member Variabel
Konversi Prosedural ke OOP 1.Pastikan program sudah terbagi menjadi fungsi-fungsi/ modular. 2.Identifikasi class yang bisa dibuat. 3.Identifikasi data member dan member function untuk class yang bersangkutan. 4.Tentukan bagian private dan public class (sesuaikan dengan skenario fungsi utama). 5.Buat fungsi utamanya (void main()). a.Membuat obyek dari class. b.Menjalankan bagian public dari class.
//PROCEDURAL PROGRAMMING #include “stdio.h” void main() { int p, l, t, volume; printf(“Program Balok\n”); printf(“Masukkan P = “); scanf(“%d”, &p); printf(“Masukkan L = “); scanf(“%d”, &l); printf(“Masukkan T = “); scanf(“%d”, &t); volume = p * l * t; printf(“Volume = %d\n”, volume); } #include “iostream.h” class balok { private : int p, l, t, volume; public : void input(void) { printf(“Masukkan P = “); scanf(“%d”, &p); printf(“Masukkan L = “); scanf(“%d”, &l); printf(“Masukkan T = “); scanf(“%d”, &t); }; void hitung(void) { volume = p * l * t; }; void output(void) { printf(“Volume = %d\n”, volume); }; }; void main() {balok balokku; printf(“Program Balok\n”); balokku.input(); balokku.hitung(); balokku.output(); }
Latihan : Identifikasi class apa saja yang terdapat di dalam sistem di bawah ini serta lengkapi dengan data member dan member function untuk masing-masing class. * buat program sederhananya juga. 1.Program menghitung luas bangun-bangun bidang datar (segi tiga & persegi panjang). 2.Program konversi mata uang rupiah ke dolar (1 $ = Rp 9.000). 3.Menampilkan N bilangan genap pertama.