How to initialize Array in Constructor and access elements using an object

What is the proper syntax for accessing an array within a constructor and passing the argument into a function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 class Polynomial{
     public:
     int Array[5];
     	Array[0] = 2 * 0^4;
	Array[1] = 2 * 1^4;
	Array[2] = 2 * 2^4;
 	Array[3] = 2 * 3^4;
	Array[4] = 2 * 4^4;
	Array[5] = 2 * 5^4; };

Polynomial::Polynomial(Array[]){}

int main(){

Polynomial object; 
object.Array[]


From what I understand, any object I create using class polynomial should have access to the default values of the Array.

Please understand that I am a complete beginner.


1) Lines 4-9 ae illegal: you cannot have code in class declaration.
2) Array[5] is illegal: Array contains only 5 elements with indices 0-4.
3) 1^4 does not do exponentation.
4) There is no declaration you are trying to define on line 11
5) Array is not a type, so line 11 is invalid once again.

You need to set values for array in constructor. Or set default values using unitialization lists.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

class Polynomial
{
public:
    Polynomial() = default;
    Polynomial(int arr[]);
    int Array[5] = {2, 2, 32, 162, 512}; //Values if default constructor was used
};

Polynomial::Polynomial(int arr[])
{
    for(int i = 0; i < 5; ++i)
        Array[i] = arr[i];
}

int main()
{
    int array[] = {1, 2, 3, 4, 5};
    Polynomial obj(array);
    std::cout << obj.Array[2] << '\n';
    Polynomial obj2;
    std::cout << obj2.Array[2] << '\n';
}

Thank you so much!
Topic archived. No new replies allowed.