Skip to content

Instantly share code, notes, and snippets.

@kateolenya
Last active March 13, 2019 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kateolenya/df3f42cd15cd0b11bf447d7976729628 to your computer and use it in GitHub Desktop.
Save kateolenya/df3f42cd15cd0b11bf447d7976729628 to your computer and use it in GitHub Desktop.
Bypassing encapsulation with pointers
#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;
}
};
int main()
{
Contact Tony;
int * mobile_number_is_here = (int *)&Tony;
cout << "Mobile number: " << (*mobile_number_is_here) << endl;
int * home_number_is_here = mobile_number_is_here + 1;
*home_number_is_here = 1;
cout << "Modified home number: " << (*home_number_is_here) << endl;
Tony.print_numbers();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment