I'm writing a polynomial project that requires me to utilize classes. Problem is, I have the polynomial stored in two arrays in the class, one for coefficients (float coefficientholder[10]) and one for exponents (int exponentholder[10]), and get functions (at least according to my book) are simply consisting of return commands for use in the main .cpp file.

Since you can't exactly 'return' arrays with the return command, how I am supposed to return the array of coefficients and exponents when I use poly.getcoeff() and poly.getexpn() in the main.cpp file?

Jess

You can't return an array, but you can pass an array by reference or you can return a POINTER to the first element of the array, which can generally be though of as the same thing (someone may chime in with the intricacies of the difference between a pointer and an array and I realize there are differences, but you can usually think of them as the same thing for your purposes).

How you do it is up to you and will depend on precisely how the data is stored and what exactly you are returning, but if you have something like this:

class poly
{
private:
    int coeff[10];
    int exp[10];
public:
    int* getcoeff();
};

then getcoeff() is probably this:

int* poly::getcoeff()
{
    int* firstElement = &(coeff[0]);
    return firstElement;
}

or even more simply, this:

int* poly::getcoeff()
{
    return coeff;
}

- First you should be using std::vectors if possible.
- Second returning the array is kind of bad OOP, since your encapsulation decreases.

Instead consider providing mechanism to accesses the coefficients. For example.

class Polynomial{
private:
 float coefficients[10];
 float exponents[10];
public:
 //...
 const float coefficientAt(int i )const;
 const float exponentsAt(int i)const;
};

or something of that nature. But you would be probably better off using std::vector if possible.

Or consider providing iterator-like interface. For example :

class Polynomial{
private:
 float coefficients[10];
 float exponent[10];
public:
//...
 const float* coefficientsBegin()const { return coefficients; }
 const float* coefficientsEnd()const{ return coefficients + 10; }
//...
}

Edited 5 Years Ago by firstPerson: n/a

Comments
Good adivce.
This article has been dead for over six months. Start a new discussion instead.