GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 21-Mar-2006, 22:39
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

in great need of creating polynomial class


ok... i have an assignment due in 14 hours and am having trouble creating and implementing a polynomial class. i have a few strict rules to follow. i will first start out by explaining what i expected and what i am and am not allowed to do.

my instructor has created the main program, some of the Poly.h, and exceptionClass.h. I am to finish poly.h, and implement Poly.cc on my own. i will only turn in Poly.h and Poly.cc. I am not allowed to make any changes to the main program or to the display function in Poly.h, and Poly.cc.

The polynomial will only consist of one variable, eg.. only an x (not an x and y for instance).

I must create the interface file Poly.h which MUST contain a basic constructor, a copy constructor, operator assignment, operator +, operator *,degree, and display.

the basic constructor should contain 2 arguments, a pointer to and integer array, and an int which is the number of non zero terms. the integer array contains the non zero elements in decreasing order of degree. each term consists of the degree followed by the term. for example, 3x^5 + 2X^2 + x..
would be represented as [5, 3, 2, 2, 1, 1].

cinPoly () is provided in the main program to obtain these two pieces of info.

the degree function will return the highest degree of the polynomial( which will always be the first element here). the private member of the Class must not be changed and none may be added. i may add public members and member functions as needed. the private member is a pointer to an integer and must stay that way.

i am not understanding how my class actually will create the polynomial. My main misunderstanding is how to create and use the constructor to create a polynomial object, and how everything relates to the operator over loads. i am in the process of doing the operators (im not being lazy i promise).

i would appreciate if anyone can walk me through this process. i have been working on Poly.h and Poly.ccand will show all codes below...

Poly.h...

CPP / C++ / C Code:

  

#ifndef Poly_H
#define Poly_H

#include <stdio.h>
#include <iostream.h>

class Poly
{
   public:
      Poly(int* const intptr, int nzero);    // constructor
      Poly(const Poly&);                     // copy constructor
      int degree();
      int getpol() const { return *pol }
      void display() const;
      Poly operator+ (const Poly&);          // operator overload to add 2 polys
      Poly operator* (const Poly&);          // operator overload to multiply 
      Poly operator= (const Poly&);          // assignment overload
      
   private:
      int *pol;                              // points to first element
};

#endif



Poly.cc...

CPP / C++ / C Code:



#include "Poly.h"
#include <iostream.h>

Poly::Poly(int * const intptr, int nzero)
{}


Poly::Poly(const Poly& rhs)
{
   pol = new int;
   *pol = rhs.getpol();
}


int Poly::degree()
{
   return (*pol);
}


Poly Poly::operator+ (const Poly & rhs)
{
   


void Poly::display() const
{
   int *p = pol + 1;
   int d = degree(),e=d;
   if (e == 0)
   {
      cout << "(0 " << *p << ")" << "\n";
      return;
   }
   cout << "(";
   while (d >= 0)
   {
      if (*p != 0)
      {
         if (d < e) cout << ", ";
         cout << d << "  " << *p;
      }
      d--; p++;
   }
   cout << ")\n";
}




           


exceptionClass.h...

CPP / C++ / C Code:

/*
   This file defines all the exception classes that may be
   thrown by the program.
*/

#ifndef EXCEPTIONCLASS_H
#define EXCEPTIONCLASS_H

#include <string>

class wrongData
{ public:
     wrongData(const string& msg)
        /* purpose: constructor to create a wrongData exception object.
           parameters: msg -- the error message.
           requirement: None.
           promise: the error message has been sent.
           exception: No.
        */
      :err(msg)  {}

      string errorMsg() {return err;}
         /* purpose: to return the stored error message.
            parameters: No.
            requirement: None.
            promise: the error message is returned.
            exception: No.
         */
   private:
      string err;   // the error message
};

#endif
       


and main.cc...

CPP / C++ / C Code:

// DO NOT MODIFY OR CHANGE THE CONTENTS OF THIS FILE.  YOUR CLASS/CODE
// MUST COMPILE WITH THE GIVEN CODE AS IS.
// Test program for testing class Poly

#include <iostream.h>
#include <stdlib.h>
#include <string>

#include "exceptionClass.h"
#include "Poly.h"

int* cinPoly(int& len);

void main()
{
   cout << "A simple program for testing polynomial\n";
   
   string option = "2";
   while (option != "1")
   {
      cout << "----------------------------------------\n";
      cout << "choose:\n";
      cout << "1   (to exit)\n";
      cout << "2   (to add two polynomials, p1+p2)\n";
      cout << "3   (to multiply two polynomials, p1*p2)\n";
      cout << "4   (p1*p2+p3)\n";
      cout << "5   (p1+p2+p3)\n";

      cin >> option;
      switch (int choice = atoi(option.c_str()))
      {
         case 1:
            break;
         case 2: case 3: case 4: case 5:
         {
            int *temp1 = NULL, *temp2 = NULL, *temp3 = NULL;
            Poly *poly1 = NULL, *poly2 = NULL, *poly3 = NULL;
            try
            {
               int len;
               cout << "Please input the first polynomial:" << endl;
               temp1 = cinPoly(len);
               poly1 = new Poly(temp1,len);
               (*poly1).display();
               cout << "Please input the second polynomial:" << endl;
               temp2 = cinPoly(len);
               poly2 = new Poly(temp2,len);
               (*poly2).display();

               Poly res;

               if (choice == 2)
                  res = *poly1 + *poly2;
               else if (choice == 3)
                  res = *poly1 * *poly2;
               else
               {
                  cout << "Please input the third polynomial:" << endl;
                  temp3 = cinPoly(len);
                  poly3 = new Poly(temp3, len);
                  (*poly3).display();
                  if (choice == 4)
                     res = *poly1 * *poly2 + *poly3;
                  else
                  {
                     Poly tempRes(*poly1 + *poly2 + *poly3);
                     res = tempRes;
                  }
               }
                  cout << "result = ";
                  res.display();
                  delete temp1; delete temp2; delete temp3;
                  delete poly1; delete poly2; delete poly3;
            }
            catch (wrongData& a)
            {
               delete temp1; delete temp2; delete temp3;
               delete poly1; delete poly2; delete poly3;
               cout << a.errorMsg();
            }
            break;
         }
         default:
            cout << "ERROR: invalid input: " << option << "\n";
            break; 
      }   // end case
   } // end while
   cout << "program exited successfully" << endl;
} //end main

int* cinPoly(int& len)
{
   cout << "Please input the # of non zero terms in the polynomial:";
   cin >> len;
   int len2 = 2 * len;
   // programming error: no checking on len, if < -1, program will 
abort.
   // It is because the length of an array cannot be negative.
   int* res = new int[len2];
   if(len != 0)
      cout << " Please input the non zero terms of the polynomial: 
degree, coefficient:" << endl;
   for (int i = 0; i < len2; i++)
      cin >> res[i];
   return res;
}



there we go. ANYTHING anyone can do to help is greatly appreciated. Please help me out. thank you.
  #2  
Old 22-Mar-2006, 09:40
QED's Avatar
QED QED is offline
Member
 
Join Date: Feb 2005
Location: Hudson Valley, NY
Posts: 231
QED is a jewel in the roughQED is a jewel in the roughQED is a jewel in the rough

Re: in great need of creating polynomial class


Here is a rough list of things that I see need attention:
  1. Your basic constructor (which you have yet to define) must create a new integer array (the first element of which will be pointed to by the pointer pol) and copy the contents of the input array to your new array. See your instructors code for cinPoly() to get an idea of how to do this.
  2. Your copy constructor should also create a new array and copy the contents of the source Polynomial's array. What you have now simply copies the pointer, meaning that the new Polynomial's pointer pol points to the same memory location. Not what you want, since when one Polynomial is destroyed, the other then contains an invalid pointer.
  3. Your assignment operator should return a reference to a Polynomial, rather than just a Polynomial.
  4. Your requirements mention nothing about a getpol() method, and none of the other code seems to use it. In addition, it appears that getpol() does exactly what degree() should do. I would simply rename getpol() to degree().
  5. Your include statements should be #include <cstdio> and #include <iostream> if you are programming in C++.
  6. Your addition and multiplication methods can probably be made const since they should not be modifying the two Polynomials being added/multiplied.
If you have more specific questions, or you run into compile-time or run-time errors, please post them and I'll see what I can make of it.

Matthew
__________________
I was born not knowing and have only had a little time to change that here and there. -- Richard P. Feynman

Boris Podolsky: James! How's the rat business?
James Moreland: Well, actually it's mostly students I'm experimenting on now.
Kurt Gödel: My God, the mazes must be enormous.
  #3  
Old 22-Mar-2006, 23:57
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

Re: in great need of creating polynomial class


Ok... the assignment has passed now and i figure i didnt do too well on it. But, i still want to learn and understand how to do it. i will start off by saying that i am confused how the constructor should create a Poly object with the 2 parameters...

(i) a pointer to an integer array
(ii) the number of non zero terms

now, i understand that when i create the object the pointer will point to the address of the first element in the array i am trying to create. The number of non zero terms can be multiplied by 2 to get the length of the array.

my trouble i think, is getting the actual values into the array created.

if i am not mistaken, if this is done i have created my Poly object correctly?

can someone take me a step further? im am still confused by this although typing this reply has added some spark in my brain.
  #4  
Old 23-Mar-2006, 09:03
QED's Avatar
QED QED is offline
Member
 
Join Date: Feb 2005
Location: Hudson Valley, NY
Posts: 231
QED is a jewel in the roughQED is a jewel in the roughQED is a jewel in the rough

Re: in great need of creating polynomial class


As I mentioned above, look at the function cinPoly for guidance:
CPP / C++ / C Code:
int* cinPoly(int& len)
{
    .
    .
    .

    int* res = new int[len2]; // this is where the array is created

    // the loop below is where the contents are assigned
    if(len != 0)
        cout << " Please input the non zero terms of the polynomial: degree, coefficient:" << endl;
    for (int i = 0; i < len2; i++)
        cin >> res[i];
    return res;
}

How might you use a similar approach in your constructor? How about:
CPP / C++ / C Code:
Poly::Poly(int * const intptr, int nzero)
{
    int len = 2 * nzero;  // array must contain degree & coeff for each term

    pol = new int[len];  // see how we create a dynamic array, like above?
    // note: at this point the array contents are uninitialized,
    // which means that the array contains "garbage"

    // this loop is analogous to the one in cinPoly
    // except that we are copying from one array to another,
    // instead of reading from cin
    for (int i = 0; i < len; ++i)
        pol[i] = intptr[i];
}

The copy constructor will do something similar, except that it will get the array ptr and size from another polynomial. If you pay close attention, you'll realize that this means that your Polynomial class is missing something, namely a length or size variable. So, you'll need to add that before you can properly implement the copy constructor. Give this a try.

Matthew
__________________
I was born not knowing and have only had a little time to change that here and there. -- Richard P. Feynman

Boris Podolsky: James! How's the rat business?
James Moreland: Well, actually it's mostly students I'm experimenting on now.
Kurt Gödel: My God, the mazes must be enormous.
  #5  
Old 23-Mar-2006, 13:20
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

Re: in great need of creating polynomial class


now i understand that cinPoly reads in the values for the polynomial. i understand why you multiply nzero by two, but i am confused by the dynamic allocation.

for this piece of code...

CPP / C++ / C Code:

pol = new int [len];


i see that it will dynamically allocate memory for the (size of int) * len. basically it will allocate memory for my array. Will pol still point to the first element in the array?

and as for the for loop i see that the elements of parameter (intptr) passed in are copied to pol for each element in the array. Thus creating a polynomial object?

So can anybody clear up the line of code above for me? Does pol point to the first element of the array? It seems it must for the code above to work the way i am thinking. Thank you all.
  #6  
Old 23-Mar-2006, 13:31
QED's Avatar
QED QED is offline
Member
 
Join Date: Feb 2005
Location: Hudson Valley, NY
Posts: 231
QED is a jewel in the roughQED is a jewel in the roughQED is a jewel in the rough

Re: in great need of creating polynomial class


Quote:
Originally Posted by fadedg2
Will pol still point to the first element in the array?
Yes, it will.

Quote:
and as for the for loop i see that the elements of parameter (intptr) passed in are copied to pol for each element in the array. Thus creating a polynomial object?
Yes, that's essentially correct. I mean, if you don't copy the data, or even don't allocate the array, there is still a Polynomial object created. It's just that it's not what we would consider a proper Polynomial, since either the array contains garbage (uninitialized) or the pol pointer doesn't point to allocated memory.

Matthew
__________________
I was born not knowing and have only had a little time to change that here and there. -- Richard P. Feynman

Boris Podolsky: James! How's the rat business?
James Moreland: Well, actually it's mostly students I'm experimenting on now.
Kurt Gödel: My God, the mazes must be enormous.
  #7  
Old 23-Mar-2006, 23:13
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

Re: in great need of creating polynomial class


Thank you for the assistance on the constructor. i understand it much better now. Now i am working on the copy constructor. i have made changes to it. i feel i am much closer.

the code below represents my copy constructor...

CPP / C++ / C Code:

Poly::Poly(const Poly& rhs)               // implementation of copy constructor
{
   pol = new int[len];
   int* npol = rhs.getpol();
   
   
   for (int i = 0; i < len; i++)
      pol[i] = npol[i]; 
}


here is what i am trying to do. the polynomial is passed in by alias (rhs). initially i allocate memory for my "copied" polynomial. here is where i am unsure... i use a public member function to access and return the address of the first element in rhs. Is this possible to use a member function within another member function? the result is stored in npol. which is a pointer to an integer, just as pol. Then i do a similar loop as used before to copy the element from the passed in polynomial to the copy of the polynomial.

Is my reasoning correct? If i cannot use member functions withen member functions, how can i access the private members of a class?

thank you.
  #8  
Old 27-Mar-2006, 00:44
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

Re: in great need of creating polynomial class


i cant really test the constructor and copy constructor in my "assignment" because every thing has to work with the instructors main program. and i have still got to get my operator functions to work. so either way it will not compile. I think my copy constructor is correct. Can i get a second opinion please? Also can some body answer my question about using the member functions withen the class for other functions and constructors? thank you.
  #9  
Old 27-Mar-2006, 08:29
QED's Avatar
QED QED is offline
Member
 
Join Date: Feb 2005
Location: Hudson Valley, NY
Posts: 231
QED is a jewel in the roughQED is a jewel in the roughQED is a jewel in the rough

Re: in great need of creating polynomial class


If you encounter compile-time errors, please post the error messages verbatim. Chances are that if you don't understand the message enough to find the mistake, then you are unlikely to explain it very well in your own words.

Looking at the code I can see one problem in the copy constructor. You are right that you are "much closer". Very close, in fact. The problem is len. Inside the copy constructor, what does len mean? The compiler doesn't know. There is not parameter named len, you have not declared a local variable named len, and probably there is neither a global nor member variable named len.

In other words, similar to the member variable pol in your Polynomial class, you need an rhs Polynomial to the new one being constructed.

Hope that makes sense.

Matthew
__________________
I was born not knowing and have only had a little time to change that here and there. -- Richard P. Feynman

Boris Podolsky: James! How's the rat business?
James Moreland: Well, actually it's mostly students I'm experimenting on now.
Kurt Gödel: My God, the mazes must be enormous.
  #10  
Old 27-Mar-2006, 19:55
fadedg2 fadedg2 is offline
Junior Member
 
Join Date: Sep 2005
Posts: 35
fadedg2 is on a distinguished road

Re: in great need of creating polynomial class


Quote:
Originally Posted by QED
In other words, similar to the member variable pol in your Polynomial class, you need an rhs Polynomial to the new one being constructed.

Hope that makes sense.


im not really sure what your saying here, but i am having trouble figuring out how to incorporate the length of the polynomial i am trying to copy into my new polynomial. I am trying to figure it out. Any suggestions here? That may be what you are trying to say but i am not understanding.
 
 

Recent GIDBlogOnce again, no time for hobbies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
determinant algorithms Blake C++ Forum 11 13-Mar-2006 19:36
polynomial program jake_jeckel C++ Forum 0 29-Oct-2005 15:16
Error C2146: syntax error : missing ',' before identifier 'C4' mattchew008 C++ Forum 2 19-Dec-2004 07:06
problem with creating class mohammed C++ Forum 1 11-Oct-2003 10:04

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 10:35.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.