Reputation: 314
HelloI got a problem when i compiled my program. Why the pointer intArray gives different addresses in constructor and member function display() in same object?Thank you!
#include<iostream>
using namespace std;
class MyClass
{ private:
int* intArray;
int arraySize;
public:
MyClass(int*,int);
~MyClass()
{delete []intArray;};
void display();
};
MyClass::MyClass(int intData[],int arrSize)
{ int *intArray = new int[arrSize];
cout<<intArray<<" "<<endl;
};
void MyClass::display()
{ cout<<intArray<<" "<<endl;
}
int main()
{ int Data[10]={9,8,7,6,5,4,3,2,1,0};
MyClass obj1(Data,10);
obj1.display();
}
Upvotes: 0
Views: 75
Reputation: 254471
In the constructor, you declare a local variable which hides the member. Both members are left uninitialised, so calling display
will show the uninitialised value.
You probably want something along the lines of
MyClass::MyClass(int intData[],int arrSize) :
intArray(new int[arrSize]),
arraySize(arrSize)
{
// assuming the input array specifies initial values
std::copy(intData, intData+arrSize, intArray);
}
Since you're dealing with raw pointers to allocated memory, remember to follow the Rule of Three to give the class valid copy semantics. Then, once you're happy with your pointer-juggling skills, throw it away and use std::vector
instead.
Upvotes: 7