• Advertisement

Archived

This topic is now archived and is closed to further replies.

getting an array from a class

This topic is 6450 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi I have a class defined that has as one of it''s private members
int *nums 
this is later initialized into an array of a certain length. For various reasons, i need to be able to retrieve this raw variable, the array, through a function. Basically what i want to know how to do is make a variable in my main program and through calling the class''s member functions fill this variable out so it''s identical to the nums array. thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
    
class foo
{
private:
int* nums;
public:
int* GetNums()
{ return nums; }
};

int main()
{
foo f;
int* p;
p = f.GetNums();
}

Share this post


Link to post
Share on other sites
[update] Damn! mhkrause beat me by 19 seconds! [/update]

I would say make it public, too. I mean, if you need it outside your class, that's what "public" is for.

But here's what you asked for:


class CYourClass {
int* nums;
public:
int* GetPointer(){ return nums; }
};

main(){
CYourClass yc;
// initialize nums into array
int* g_nums = yc.GetPointer();
}


Edited by - Eric on June 26, 2000 10:21:23 PM

Share this post


Link to post
Share on other sites
Although it''s possible (using the method the guys in the previous posts stated), it goes against the basic rules of OO programming: data hiding and encapsulation. If you''re gonna do it like that, you''d probably better use plain C...

I suggest you do it like this:
    
class foo {
private:
int* nums;
public:
foo(int size) {
nums = new int [size];
}
~foo() {
delete [] nums;
}
// Returns read-only array

const int* GetNums() const
{ return nums; }
// Element manipulation

void SetNum(int index, int value) {
// Assuming the size of your array is big enough

nums[index] = value;
}
int GetNum(int index) {
return nums[index];
}
// Or using the [] operator

int& operator [] (int index) {
return nums[index];
}
};

int main() {
foo f(100);
const int* p;
p = f.GetNums();
// Using the [] operator

f[0] = 100;
}


Dormeur

Share this post


Link to post
Share on other sites

  • Advertisement