C++ Question Arrays, Classes, Passing Functions

Hi, I'm new to C++ (maybe my code below will make it obvious) But I'm doing an Array problem and I was wondering, how would I go about passing arrays between member functions of one class? I just want to understand how classes and arrays and such work. I have yet to get to pointers but I was hoping you guys could give me a few tips on how to get started. The goal of the program is here in pseudocode
>>prompt user for size of array
>>make array
>>ask user to enter in digits (int)
>>ask user what index of array they would like to see
(if they entered 23 into the fifth index of the array, they would type 5 and 23 would come out)
>>exit when user enters in exit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

#include <iostream>

using namespace std;
class Arrays
{
    public:

        int sizeOfArray;
        void displayMessage()
        {
            cout << "Welcome to the Array Program!" << endl;
        }
        int setSize()
        {
            cout << "How big would you like your array to be? ";
            cin >> sizeOfArray;
            return sizeOfArray;

        }
        int getValues()
        {
            int arrayList[setSize()];
            int input;
            for(int i = 0; i != sizeOfArray; ++i)
            {
                int arrayList[sizeOfArray];
                cout << "Enter in value number " << i + 1 << ":";
                cin >> input;
                arrayList[i] = input;
            }
            return arrayList[0];

        }
        int printQuestion()
        {
            int input;
            cout << "Enter in the space number you would like to view: ";
            cin >> input;
            for(i = 0; i != input; ++i)
            {
                getValues
            }
            }
        }
        void printSpace(int space, arrayList)
        {
            cout << arrayList[space] << endl;
        } 
  /*  private:
        int arrayList[setSize()];
*/
};


int main()
{

    Arrays arrayClass;
    arrayClass.displayMessage();
    arrayClass.getValues();
    arrayClass.printQuestion();


}
Last edited on
Well first of all, you can't initialize any variables in your class, that is what your constructor is for. So on line 51 where you have int arrayList[setSize()], it should only read int arrayList[]. In your constructor you can prompt for a size value if you wanted to or just prompt for it in main() or something and pass the variable to the constructor. As for passing the array between different member functions of the same class... you don't need to worry about that. In any member function all variables are directly accessible. So in your class, one option would be to build your constructor as follows:
 
Arrays () {arrayList [setSize()];}


anyway there are a few other bugs in your program but I think you get the idea. let me know if you need any more help
Hi! Thanks for your quick reply slider57! I am quite the novice at this and apologize for my "noobiness" but can you explain what the line you provided does?
 
Arrays () {arrayList [setSize()];}
Okay! So I sort of cleaned up my program and here it is...but it still doesnt work :( I don't know why...It seems like the arrayList is resetting itself or something because I get really weird data when I test the program. For example this is me interacting with it...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Welcome to the Array Program!
How big would you like your array to be? 5
Enter in value number 1: 546
Enter in value number 2: 34
Enter in value number 3: 76
Enter in value number 4: 34
Enter in value number 5: 76
5
2130567168
0
2686824
4198582

Process returned 0 (0x0)   execution time : 7.754 s
Press any key to continue.


Here is the program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

using namespace std;
class Arrays
{
    public:

        int arrayList[];
        int sizeOfArray;
        void displayMessage()
        {
            cout << "Welcome to the Array Program!" << endl;
        }
        int setSize()
        {
          //  int sizeOfArray;
            cout << "How big would you like your array to be? ";
            cin >> sizeOfArray;
            return sizeOfArray;

        }
        int getValues(int size)
        {
            int arrayList[size];
            int input;
            for(int i = 0; i != size; ++i)
            {

                cout << "Enter in value number " << i + 1 << ":";
                cin >> input;
                arrayList[i] = input;
            }
            return arrayList[0];

        }
        void printTest(int size)
        {
            for(int i = 0; i < size; ++i)
            {
                cout << arrayList[i] << endl;
            }
        }
};

int main()
{
    Arrays arrayClass;
    arrayClass.displayMessage();
  //  arrayClass.setsize();
    arrayClass.getValues(arrayClass.setSize());
    arrayClass.printTest(arrayClass.sizeOfArray);
}

the line i gave you is called a constructor. when you build a class you need to 'construct' it (with the constructor). as you have it written now you are using the default constructor the compiler gives you, which isnt really a good idea.

you dont really need to return or pass any values because you will always have access to any member variables in member functions of the class. So i'd prolly make all your functions void and not return anything.

Dont declare another arrayList in your function getvalues(), you already have one. Also when I ran your program I ran into an interesting error which was redeclaring the sizeOfArray value. So if you run into that I got around it by declaring a const variable and set it to sizeOfArray and used that in the for loop. Also, make sure to use that constructor so you can get your array initialized.
Oh also, the reason for the output of the program is you declared that int of arrayList in your getValues() function, when it went out of scope (returned from function) it was destroyed. So you are outputting your OTHER array that you have already declared (in the public section of your class) and there is no 'good' values in it, so you are outputting garbage.
Thank you so much slider57 for helping me! I have 98% of the program finished. JUST ONE SMALL BUG. I can NEVER get the 2nd value of any size array to print out. It just prints out the size of Array when I ask for the 2nd value. Here is what happens:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Welcome to the Array Program!
How big would you like your array to be? 3
Enter in value number 1:12
Enter in value number 2:36
Enter in value number 3:25
To exit, enter in a number greater than the
amount of spaces in your list, in this case: 3
Which value would you like to view? 2
3
Which value would you like to view? 1
12
Which value would you like to view? 3
25
Which value would you like to view? 56

Process returned 0 (0x0)   execution time : 49.152 s
Press any key to continue.


Here is my code....hope you can help! This is a peculiar problem.....
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

#include <iostream>

using namespace std;
class Arrays
{
    public:
        int arrayList[];
        int sizeOfArray;
        void displayMessage()
        {
            cout << "Welcome to the Array Program!" << endl;
        }
        Arrays()
        {
            displayMessage();
            arrayList[setSize()];
           // const int levels;
        }


        int setSize()
        {
          //  int sizeOfArray;

            cout << "How big would you like your array to be? ";
            cin >> sizeOfArray;
            return sizeOfArray;



        }
        int getValues()
        {

            int input;
            const int levels = sizeOfArray;
        //    cout << sizeOfArray << "size"<<endl;// debug line
            for(int i = 0; i < levels; i = i + 1)
            {

                cout << "Enter in value number " << i + 1 << ":";
                cin >> input;
                arrayList[i] = input;
            }

            return(levels);
        }
        const int setConst()
        {

            const int x = getValues();
            return x;

        }
};

int main()
{
    Arrays arrayClass;
    const int localvar = arrayClass.setConst();
    cout << "To exit, enter in a number greater than the" << endl;
    cout << "amount of spaces in your list, in this case: " << localvar << endl;
    while (1)
    {
        int input_two;

        cout << "Which value would you like to view? ";
        cin >> input_two;

        if (input_two > localvar)
            {
                break;
            }
        input_two = input_two - 1;
        cout << arrayClass.arrayList[input_two] << endl;


}

}
You did run into an interesting error. I realized that I have never initialized a static array so the error you had was freaking me out. I did a little research and noticed (apparently) that there are issues with using static arrays in classes. So, to fix the error I made arrayList a pointer.

Youll notice in the code I just uploaded that in the constructor on line 69 I used the 'new' operator, declared a type of int's and made that an array of num, [num]. The new operator returns an address so I just assigned that address to the pointer. You will also notice that on line 71 I declared a destructor. On line 73 I erased (or gave back the memory to the operating sytem) the array that the pointer was pointing to. I changed the while loop case on line 38 (also made that a part of the member function getValues) so that, just like you had it, if they enter a value greater than the array it returns, or if they enter a value that is not an integer (as denoted by cin.fail()) it will also return.

The rest of it was just cleaning it up and putting the member function code underneath main so that the class was easier to read. Sorry if i ruined the program for you. You can take out the bits that you want and ignore the rest.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>

using namespace std;
class Arrays
{
public:
   Arrays (int num); // constructor
   ~Arrays (); // destructor
   void displayMessage(); // displays welcome message
   void setValues(); // retrieves values from user and sets them to the array
   void getValues(); // allows a user to specify element to view
   void printTest(); // prints out all values in all elements
private:
   int* arrayList; // pointer to array of a user defined size
   int sizeOfArray; // size of the array

};

int main()
{
   int size = 0;

   cout << "How big would you like your array to be: ";
   cin >> size;

   Arrays arrayClass (size);
   arrayClass.displayMessage();
   arrayClass.setValues();
   arrayClass.getValues();
   arrayClass.printTest();

   return 0;
}
void Arrays :: getValues()
{
   int input_two = 0;

   while (!cin.fail() || input_two >= sizeOfArray)
   {
      cout << "Which value would you like to view? ";
      cin >> input_two;

      input_two = input_two - 1;
      cout << arrayList[input_two] << endl;
   }
}
void Arrays :: setValues()
{
   for(int i = 0; i < sizeOfArray; i++)
   {
      cout << "Enter in value number " << i + 1 << ":";
      cin >> this->arrayList[i];
   }
}
void Arrays :: printTest()
{
   for(int i = 0; i < sizeOfArray; i++)
   {
      cout << arrayList[i] << endl;
  }
}
void Arrays :: displayMessage()
{
   cout << "Welcome to the Array Program!" << endl;
}
Arrays :: Arrays (int num)
{
   sizeOfArray = num;
   arrayList = new int [num];
}
Arrays :: ~Arrays ()
{
   delete [] arrayList;
}


Sorry I wasn't able to fix the original error and just gave you a workaround. Anyway, if you have any other questions just let me know.

P.S. - I also appreciate how grateful you are for other peoples help here on the site. That is one of my biggest pet peeves is ungrateful people.
Thank you so much! I can't believe you put out the time to do this for me. I'm really glad you did but I was just wondering about some questions that kind of confuse me a little.



1) What is the function of the constructor/destructor?
2) How do you usually know what to put under private and under public?
3) In the setValues function, what does "cin >> this->arrayList[i];" do exactly?(I can guess but Id like to know how the compiler interprets it haha)
4) Also can you tell me whats going on with cin.fail? Specifically this line in getValues "while (!cin.fail() || input_two >= sizeOfArray)".
5) How come printTest never executes even though it is called?

Sorry for the noob questions, I'm really grateful that you're helping out a noob programmer like me haha.
1)
Constructor - The function of the constructor is to create your object. Just like a house needs to be constructed before you live in it, so does your object need to be constructed before you can use it. So in the constructor we usually will define variables to default values or build other variables so they are ready for use.
Destructor - The function of a destructor is to destroy parts of an object that otherwise couldnt be destroyed by the default destructor (the one that the compiler automatically creates for you). Usually you only build a destructor if you have dynamically allocated memory from the heap (used the new operator, which asks the operating system for memory during runtime of your program). If you don't destroy the the dynamically allocated type (such as int, or string or even your class Arrays), you have something called a memory leak. memory leaks could cause your system to slow down or eventually crash if it is bad enough. So when I wrote arrayList = new int [num], I knew that when my class went out of scope I would need to free that memory up. That is why I built a destructor in the class.

2) When you are programming a class, such as maybe a character in a game, you dont want a programmer (or even yourself) to be able to screw up the characteristics of your character. So, you make certain information private so you dont have direct access to it (not being able to use the private member data outside the member functions). It provides a layer of protection and security for your variables. Good practice is to put all your variables in the private section, and even some functions that you dont want other people to be able to directly call.

3) Well cin >> this->arrayList[i] is just putting whatever the user typed in into the array at element i. So if I was 1 then whatever the user typed in would go to the element 1 in the array. In all reality you dont need 'this->'. It is called the 'this' pointer and is created for you to use everytime a object calls its member function. I just use it to help denote what is the objects member variables so I dont get confused. The arrow operator (->) is a quick way to dereference the pointer (dereference something is saying give me whatever is at the address the pointer is pointing to. In this case it was the calling object.). You can just use arrayList [i] though if you are not comfortable with the 'this' pointer.

4) If you ask a user to input something, that person has the option of inputting whatever is on his/her keyboard. When you ask the user to input something the variable that will catch their input is called input_two, which you delcared to be of type int. So you are expecting an integer only. Well if the user types, 'hello' that cannot be caught by an integer type variable. So cin says whoa thats not going to work and sets its fail bit to true (which means some input failed). You can check to see if the fail bit is set to true by calling cin's member function fail(). It works just like any of your member functions except this returns a boolean value (either true meaning fail bit is set or false meaning fail bit is not set).

5) printTest() was called when I ran it.

By the way I noticed a glaring error that I made in the program:
You are going to need to change the entire getvalues() function to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void Arrays :: getValues()
{
   int input_two = 0;
   bool key = true;
   while (key)
   {
      cout << "Which value would you like to view? ";
      cin >> input_two;

      if (!cin.fail() && input_two <= sizeOfArray)
      {
         input_two = input_two - 1;
         cout << arrayList[input_two] << endl;
      }
      else
      {
         cin.clear();
         cin.ignore (256, '\n');
         key = false;
      }

   }
}


if you want it to work properly. Haha, no ones perfect I guess. By the way clear() and ignore are also member functions of cin. clear() resets the fail bit and ignore extracts characters out of cin's buffer so they dont mess up your program.
Topic archived. No new replies allowed.