I have two classes. class1
and class2
. class2
creates an array with elements that are of type class1
. class2
has a member that points to that array. I can access the pointer with class 2's
getpointer
method, but I get unexpected results when I try to use the pointer to access members of the array's elements.
Here's the code:
#include <iostream>
using namespace std;
class class1{
int a;
int b;
public:
class1(){}
class1(int x, int y){a = x; b = y;}
int geta(){return a;}
int getb(){return b;}
};
class class2{
int c;
int d;
class1 *e;
public:
class2(int x, int y){c = x; d = y;}
void setE(){
class1 arr[3];
class1 arrTemp (0,0);
arr[0] = arrTemp;
class1 arrTemp1 (1,1);
arr[1] = arrTemp1;
class1 arrTemp2 (2,2);
arr[2] = arrTemp2;
cout << "Element 1, A = ";
cout << arr[0].geta() << endl;
cout << "Element 1, B = ";
cout << arr[0].getb() << endl;
cout << "Element 2, A = ";
cout << arr[1].geta() << endl;
cout << "Element 2, B = ";
cout << arr[1].getb() << endl;
cout << "Element 3, A = ";
cout << arr[2].geta() << endl;
cout << "Element 3, B = ";
cout << arr[2].getb() << endl;
class1 *pt;
pt = &arr[0];
e = pt;
}
class1* getpointer(){return e;}
};
int main(){
class2 testObj (1,2);
testObj.setE();
class1 *objPointer = testObj.getpointer();
class1 tempclass1;
tempclass1 = *(objPointer + 0);
cout << "Element 1, A = ";
cout << tempclass1.geta() << endl;
cout << "Element 1, B = ";
cout << tempclass1.getb() << endl;
tempclass1 = *(objPointer + 1);
cout << "Element 2, A = ";
cout << tempclass1.geta() << endl;
cout << "Element 2, B = ";
cout << tempclass1.getb() << endl;
tempclass1 = *(objPointer + 1);
cout << "Element 3, A = ";
cout << tempclass1.geta() << endl;
cout << "Element 3, B = ";
cout << tempclass1.getb() << endl;
};
This is the output:
Element 1, A = 0
Element 1, B = 0
Element 2, A = 1
Element 2, B = 1
Element 3, A = 2
Element 3, B = 2
Element 1, A = 0
Element 1, B = 0
Element 2, A = -360531408
Element 2, B = 29391
Element 3, A = -360531408
Element 3, B = 29391
With the first set of cout
statements I verify that the data is going into the array correctly.
It looks like I get the correct data for the first element, but after that what I get with the pointer is completely different from the actual array. I'm very new to C++, but I thought that *(Pointer + i)
was equal to arr[i]
.