Accessing Private Members in C++

Thursday, December 15, 2005

It had been long since I last wrote something technical. My friends are continuously bugging me for writing something technical. Before my technical image vanishes away in trek and social activites, here is some technical stuff..

This code demonstrates how we can access Private Data Members in C++. This is a major flaw in OOP in C++..


/* CODE BY DINESH SONI
dinesh.soni@gmail.com
9890897198
*/

#include <iostream.h>
#include <string.h>
#include <conio.h>

class person
{
private:

char name[40];
char grade;
int age;

public:

person(char* nam="Default",char gr='A',int saal=25)
{
strcpy(name,nam);
grade=gr;
age=saal;
}

friend ostream& operator <<(ostream& s,person b);
};

ostream& operator <<(ostream& s,person b)
{
s<<"Name :"<<b.name<<endl
<<"Rating :"<<b.grade<<endl
<<"Age :"<<b.age<<"\n\n\n";
return s;
}

struct hack
{
char name[40];
char grade;
char age;
};


void main()
{
clrscr();
person bc;
cout<<bc;
void* ptr=&bc;
struct hack* person_1=(hack*)ptr;
person_1->grade='F';
person_1->age=56;
cout<<bc;
strcpy(person_1->name,"Dinesh Soni");
person_1->age=21;
person_1->grade='A';
cout<<bc;
getch();
}

- Dinesh Finally completed this scribble at 7:50 PM  

0 people thought of commenting on this:

Post a Comment