0

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();
}
Roaid
  • 316
  • 5
  • 17
  • 6
    because they're 2 different variables? You are declaring a new intArray inside the construct of MyClass – dfranca Apr 07 '15 at 16:02
  • Here you declare a new lokal variable int *intArray = new int[arrSize]; with the same name as your member variable you should write intArray = new int[arrSize]; – nobs Apr 07 '15 at 16:05
  • The problem is resolved.Thank you for help. – Roaid Apr 07 '15 at 16:11
  • @Roaid When an answer resolves your problem, you should [accept it](http://stackoverflow.com/help/someone-answers) (using the green tick-mark next to it). That's the SO way of saying "Resolved, thanks." – Angew is no longer proud of SO Apr 07 '15 at 16:24

1 Answers1

7

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.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644