Last active
March 13, 2019 14:33
-
-
Save kateolenya/8532014688d2794a83971652d8c08c18 to your computer and use it in GitHub Desktop.
Bypassing encapsulation with typecast to struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Contact | |
{ | |
private: | |
int mobile_number; // private variable | |
int home_number; // private variable | |
public: | |
Contact() // constructor | |
{ | |
mobile_number = 12345678; | |
home_number = 87654321; | |
} | |
void print_numbers() | |
{ | |
cout << "Mobile number: " << mobile_number; | |
cout << ", home number: " << home_number << endl; | |
} | |
}; | |
struct Contact_struct | |
{ | |
int mobile_number; | |
int home_number; | |
}; | |
int main() | |
{ | |
Contact Tony; | |
Contact_struct * structured_Tony; | |
Tony.print_numbers(); | |
structured_Tony = (Contact_struct *) & Tony; | |
structured_Tony->mobile_number = 20; | |
structured_Tony->home_number = 30; | |
Tony.print_numbers(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment