OOP Demo

Demo 1 - Abstraction

class Phone.

1234567891011121314151617
#include <iostream> using namespace std; class Phone { int id; char serialNumber[50]; int price; }; int main() { Phone phone1; Phone phone2; cout << sizeof(Phone) << " " << sizeof(phone1) << " " << sizeof(phone2) << endl; return 0; }

Demo 2 - Abstraction

Attributes & Methods

123456789101112131415161718192021222324
class Phone { int id; char serialNumber[50]; int price; void increasePrice(int p) { price += p; } int getPrice() { return serialNumber[0] = 'u' ? price : price / 2; } }; int main() { Phone phone; phone.price = 650; phone.increasePrice(50); cout << phone.getPrice(); return 0; }

Demo 3 - Encapsulation

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
class Date { int day; int month; int year; }; int main() { Date dob; dob.day = 30; // invalid date dob.month = 2; dob.year = 2019; return 0; } /* #include <iostream> using namespace std; class Date { private: int day; int month; int year; public: void setDate(int d, int m, int y) { } void showDate() { cout << day << "/" << month << "/" << year << endl; } }; int main() { Date dob; int* dobHack = (int*)&dob; *(dobHack + 0) = 1; *(dobHack + 1) = 2; *(dobHack + 2) = 3; dob.showDate(); return 0; } */

*Demo Memory Alignment

123456789101112131415161718192021
class FileHeader { private: char type[4]; char secret; int width; int height; char bitDepth; char credit[5]; } #pragma pack(push, 1) class FileHeader { private: char type[4]; char secret; int width; int height; char bitDepth; char credit[5]; } #pragma pack(pop)