Search code examples
c++gnu

Accessing member array of class using containing class array through pointer - contained array of class object is private


I have as a class member an array of that class (obj) and I would like to create array of the Box class (which is the containing class) and access xyz obj[5]; through a p pointer object member of that Box class.

The obj array is private but I think I can access it using pointer. Am I correct?

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class xyz{
public:
int x;
};
class Box {

   public:
      // Constructor definition
     
      Box ()
      { 
        cout<<"without constructot"<<endl;
      }
      xyz *p=obj;   
      
   private:
    xyz obj[5];
     
};
int main()
{

    Box b[5];;
    Box *p=&b[0];
    (b+2)->(obj)->x=5;
    //cout <<(b+2)->(obj)->x<<endl;     


}

exception thrown at (b+2)->(obj)->x=5;

this

  error: expected unqualified-id before ‘(’ token
   28 |  (b+2)->(obj)->x=5;
      |         ^
    main.cpp:28:10: error: ‘obj’ was not declared in this scope      28 |  (b+2)->(obj)->x=5;
      |          ^~~

Solution

  • There are a number of issues in your code. First, I'm not sure what you are trying to accomplish using the parentheses around obj but the member access operator (->) doesn't work like that – it must be followed immediately by the member's name.

    Maybe what you want is something like this: ( (b + 2)->obj )->x = 5; ? However, the outer parentheses are not necessary in such an expression, because -> has left-to-right associativity (although you can use it for clarity).

    However, even with that modification, you are still trying to access a private member of the class from outside the definition of that class, and that is not allowed. Generally speaking, if a member is private, then you can only access it from within member functions (or friend functions) of the class.

    As a final observation: I'm not sure why you are using (b + 2) when you can just use b[2]. Did you mean to use the pointer (p) that was assigned the address of b[0] in the previous line (as in (p + 2)->obj->x = 5;)?


    As a footnote, I would strongly suggest that you read the following Stack Overflow posts:

    1. Why should I not #include <bits/stdc++.h>?
    2. Why is "using namespace std;" considered bad practice?