Sergey Kanaev
Sergey Kanaev

Reputation: 592

Access to private or protected data of class with pointer

Suppose we have two functions (not any class member):

int input_int (int *p)
{
 p[0] = 10;
 return p[0];
}

char input_char (char *p)
{
 p[0] = 5;
 return p[0];
}

And some class:

class foo {
   public:
      foo();
      void some_usefull_stuff() {
           int i = input_int( &(this->A) );
      }
   protected:
      void feature_for_usefull_stuff() {
           char chr = input_char( &(this->B) );
      }
      int A;
   private:
      char B;
};

Will functions input_char and input_int work correctly? Won't they produce segmentation fault or any exception?

Upvotes: 0

Views: 102

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258618

Yes, they will work correctly, the addresses passed to the methods are correct and point to the right types of data.

Upvotes: 1

Related Questions