C++ has a big flaw.

41 views
Skip to first unread message

Amit

unread,
Mar 27, 2025, 10:40:08 AMMar 27
to ns-dev...@googlegroups.com
C++ has a big flaw. You can change the values of the private member
variables directly by getting the pointer to the object. So, private
member variables are actually not private, they are public. Below is
the example code:

--------------------

#include <iostream>

using namespace std;

class MyClass
{

private:
int i;
int j;

public:
MyClass(int a, int b)
{
i = a;
j = b;
}

void print_data()
{
cout << endl;
cout << "i = " << i << ", j = " << j;
}

}; // end of class MyClass

int main(void)
{

MyClass myobj(1, 4);

myobj.print_data();

MyClass *m = &myobj;

//int *i_ptr = (int *)(m); // this works too
int *i_ptr = reinterpret_cast <int *>(m);
int *j_ptr = i_ptr + 1;

*i_ptr = 10;
*j_ptr = 20;

myobj.print_data();

cout << endl << endl;

return 0;

} // end of function main()

--------------------

The output is:

i = 1, j = 4
i = 10, j = 20

So, you see that the values of the private member variables ('i' and
'j') were changed directly by using pointers. So, the 'private'
keyword actually didn't serve its purpose.

Regards,
Amit

Tom Henderson

unread,
Mar 27, 2025, 10:43:48 AMMar 27
to Amit, ns-dev...@googlegroups.com
Hello Amit, I am not sure of the point of your post, but I don't think
that general critiques of C++ are within scope of this list, which is
focused on ns-3 software development discussions.

- Tom
> --
> You received this message because you are subscribed to the Google Groups "ns-developers" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to ns-developer...@googlegroups.com.
> To view this discussion visit https://groups.google.com/d/msgid/ns-developers/CAFf%2B5zhzwym%2BQ7e%2BMNeQMG1CkooELhRx-Oo3snQfpqyAZnJ0MA%40mail.gmail.com.

Reply all
Reply to author
Forward
0 new messages