#include <iostream>

using namespace std;

class emp
{
    private :        

        int i ;
	int j;

    public :

        emp( )

        {

            i = 10 ;
	    j = 50 ;

        }

		void display()
		{
			cout<<endl<<i<<"  "<<j<<endl;
		}
} ;

int main( )

{
    emp *p = new emp ;
	
    p->display();

    int *pi = (int*) p ;

    cout << *pi ;

    *pi = 20 ;

    p->display();
	
	delete p;

	return 0;
}

I have two questions...

First: Isn't the above code shows flaw/hole in the language??I am able to access the private member of the class through typecasting

Second:If you see the output of this code...it comes out to be
10 50
10
20 50
How can i change the private data member j through the typecasted pointer

Recommended Answers

All 2 Replies

>Isn't the above code shows flaw/hole in the language??
No. If C++ were designed to avoid both stupid breaking of the rules and willful/malicious breaking of the rules, the language would be a beast that nobody wanted to use. C++ protects you from your stupidity, but if you know how to sidestep the protection, that's your business.

>How can i change the private data member j through the typecasted pointer

#include <iostream>

using namespace std;

class emp {
  int i;
  int j;
public:
  emp(): i ( 10 ), j ( 20 ) {}
  void display()
  {
    cout<< i <<' '<< j <<'\n';
  }
};

int main()
{
  emp e;
  unsigned char *p =
    reinterpret_cast<unsigned char*> ( &e );
  int *pi =
    reinterpret_cast<int*> ( p );
  int *pj =
    reinterpret_cast<int*> ( p + sizeof ( int ) );

  e.display();
  ++*pi;
  --*pj;
  e.display();

  return 0;
}

That's one way you can, since you asked. But you shouldn't. Private members are private for a reason, and you should respect that. Not to mention that if you have to ask about this, you're probably not aware of the many (many!) pitfalls and potential undefined behavior of what you want to do.

Ok...thanx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.