mardi 15 décembre 2020

Why can we access private data members class using pointers, without using members friend function other members in the class?

As you know, private members can only be accessed by other members in the class

class DateClass // members are private by default
{
    int m_month; // private, can only be accessed by other members
    int m_day; // private, can only be accessed by other members
    int m_year; // private, can only be accessed by other members
};
 
int main()
{
    DateClass date;
    date.m_month = 12; // error
    date.m_day = 15; // error
    date.m_year = 2020; // error
 
    return 0;
}

But I was quite surprise that you can use pointers to access private data members. An example:

#include <iostream>  
  
class Test { 
private: 
    int data; 
  
public: 
    Test()
    {
        data = 0;
    }

    int getData()
    {
        return data;
    }
}; 
  
int main() 
{ 
    Test t; 
    int* ptr = (int*)&t; 
    *ptr = 10; 
    std::cout << t.getData(); // it will return 10
    return 0; 
}

So is this intentional? Why private members can be accessed by pointers? I'm a beginner so this question is quite stupid.

Aucun commentaire:

Enregistrer un commentaire