954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

accessing array declared within a class

hi can anybody please expalin me that can i access the array(arr) which is declared as a private member of the class(array) by using public function (display). The code is given here...

#include<iostream.h>
const int  size= 8;
class array
{
int arr[size];
int i;
        public:
array();
void display(int arr[size]);
};

array::array()
{
        i=0;
        arr[0]=21;
        arr[1]=55;
        arr[2]=16;
        arr[3]=11;
        arr[4]=51;
        arr[5]=67;
        arr[6]=5;
        arr[7]=8;
}




//traversal of an array

void array::display(int arr[size])
        {
                for(i=0;i<size;i++)
                        cout<<arr[i]<<"\t";
                cout<<endl;
        }



int main()
{
array ob1;
ob1.display(arr[8]);

return 0;
}

when i try to compile the code it gives the following error:
test.cpp:42: error: arr was not declared in this scope
please help!

thanks in advance

pdwivedi
Light Poster
37 posts since Oct 2007
Reputation Points: 8
Solved Threads: 0
 

The array is inside the class.

So it would be just
ob1.display();

And declare your member function as taking no parameters.

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

The array is inside the class.

So it would be just ob1.display();

And declare your member function as taking no parameters.

thanks salem for your quick reply but i have one more doubt as i am a beginner that what if i have diclared more than one array members in the class eg. arr1[3] then how will function know to display which array?
thanks

pdwivedi
Light Poster
37 posts since Oct 2007
Reputation Points: 8
Solved Threads: 0
 

Well that's up to the code in the display function.

Perhaps
display ( int whichArray );

For example
if it's zero, display arr
if it's one, display arr1

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

actually i want to write a code that takes array as an argument then sort and display the arrays.I have craeted the function for sorting and displaying but now i am stuck at how to pass the arrays for sorting or displaying.

pdwivedi
Light Poster
37 posts since Oct 2007
Reputation Points: 8
Solved Threads: 0
 

So why do you have an array in your class, if all you do is pass in an array to work on?

Are you sure that arr and arr1 are not just two instances of your class?

Salem
Posting Sage
Team Colleague
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You