Creating objects when the user needs them?

This is a discussion on Creating objects when the user needs them? within the C++ Programming forums, part of the General Programming Boards category; I'm practicing C++ by writing matrix manipulation programs, each one being more sophisticated than the one before. (I'm also in ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    244

    Creating objects when the user needs them?

    I'm practicing C++ by writing matrix manipulation programs, each one being more sophisticated than the one before. (I'm also in linear algebra, so matrices are of specific interest to me)

    Anyways, say I wanted the user to make as many matrices as they wanted and then bring them up when desired, but I dont' want to waste a huge amount of memory by making 30 objects at the beginning of the program.

    For example, a prompt which asks the user if they want to make another matrix. If they say yes, a new object is THEN created with the users parameters.

    Is this possible?

    Here's my code right now:

    Code:
    #include <iostream.h>
    #include <stdlib.h> // needed for system("PAUSE")
    
    class matrix
    {
          public:
          matrix(int,int);   // constructor - takes size, aXb, and fills the array with 0's
          ~matrix(); // destructor - doesn't do much, but still needed
          void ShowMatrix();
          void GetValues();
    
          private: // the following variables are private, which means they
                   // can only be changed by functions/methods within the class itself!
          int x;
          int y;
          int a;
          int b;
          int matrix_ar[8][8]; // 8x8 array
    };
    matrix::matrix(int A, int B)
    {
                    a = A;    // sets row size
                    b = B;    // set column size
                    for(x = 0; x<8 ; x++)       // fills array with 0's
                    {
                          for(y = 0; y<8; y++)
                          {
                                matrix_ar[x][y]=0;
                          }
                    }
    }
    
    matrix::~matrix()
    {
    }
    
    void matrix::ShowMatrix() // displays the matrix
    {
         for(x = 0; x<a; x++)
         {
               cout << "| ";
               for(y = 0; y<b; y++)
               {
                     cout << matrix_ar[x][y] << "\t";
               }
               cout << " |\n";
         }
    }
    
    void matrix::GetValues()
    {
         cout << "CON GRAD JOO LAY SHUNS! You've just made a NEW MATRIX!\n";
         cout << "The SIZE of your MATRIX is: " << a << "x" << b << endl;
         cout << "Now you must enter the matrix values! WHOO!\n";
         for(x = 0; x<a; x++)
         {
               for(y=0; y<b; y++)
               {
                        cout << "(" << (x+1) << ", " << (y+1) << ")\n" << endl;
                        cin >> matrix_ar[x][y];
               }
         }
    }
    
    int main(int argc, char *argv[])
    {
      // some variables...
      int a;
      int b;
    
      // program really starts here!
      cout << "Welcome!\n";
      cout << "Enter the size of your matrix:\n";
      cout << "Rows: ";
      cin >> a;
      cout << endl << "Columns: ";
      cin >> b;
      matrix matrix_A(a,b);
      matrix_A.GetValues();
      matrix_A.ShowMatrix();
      system("PAUSE");
      return 0;
    }
    P.S. -> I brought this up in my previous thread on arrays, but the one reply wasn't clear so I thought I'd create a new topic.

    Thanks!

  2. #2
    Just because ygfperson's Avatar
    Join Date
    Jan 2002
    Posts
    2,493
    research the 'new' keywork. it dynamically allocates memory for objects.

    Code:
    Object a;
    Object* p;
    p = &a; //p points to a
    p = new Object(); //p points to a block of memory containing an object
    p->dostuff();
    delete p;
    this memory is allocaed until the program exits, so you need to be careful to delete memory after you're done with it.

  3. #3
    Registered User xds4lx's Avatar
    Join Date
    Nov 2001
    Posts
    630
    Yeah you can its simple. When the user inputs what you want do
    Code:
    matrix* pcMatrix = new matrix(row,col);
    ....
    ....
    then when your done with it make sure you clean up and delete the object by doing:
    Code:
    if(pcMatrix)
        delete pcMatrix;
    "only two things are infinite, the universe and human stupidity, and im not sure about the former." - albert einstein

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Yea thats what I thought, but doesn't that require making a different pointer for every matrix?

    Or is there something I don't understand?

  5. #5
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Originally posted by ygfperson
    research the 'new' keywork. it dynamically allocates memory for objects.

    Code:
    Object a;
    Object* p;
    p = &a; //p points to a
    p = new Object(); //p points to a block of memory containing an object
    p->dostuff();
    delete p;
    this memory is allocaed until the program exits, so you need to be careful to delete memory after you're done with it.
    ahh but what if the user wants object q, r, s, t, v? Wouldn't that require making the pointers dynamically?

    Still don't understand
    Last edited by Captain Penguin; 09-13-2002 at 01:18 PM.

  6. #6
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    There's no simple way to explain this if you don't understand pointers properly. Anyway, if you want a new object just new a pointer to an object.

    eg. if i wanted to create objects only if the user wants to then i'd do this:

    Code:
    cout << "Do u want an object created on the stack?";
    if(AnswerIsYes()) //Use your own method for testing user input
    {
           Object* newObject = new Object;
    }
    
    //...
    //...
    
    delete newObject;       //delete object when you're done with it

  7. #7
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Originally posted by The Dog
    There's no simple way to explain this if you don't understand pointers properly. Anyway, if you want a new object just new a pointer to an object.

    eg. if i wanted to create objects only if the user wants to then i'd do this:

    Code:
    cout << "Do u want an object created on the stack?";
    if(AnswerIsYes()) //Use your own method for testing user input
    {
           Object* newObject = new Object;
    }
    
    //...
    //...
    
    delete newObject;       //delete object when you're done with it
    but I DO understand pointers.

    Here's exactly what I want to do:

    The user will have a menu. He will be able to create a matrix, delete a matrix, out of the blue. He will be able to create as many as he wants at one time (well, upto a certain limit). Each matrix will have its own variable name. The matrices will be able to added and subtracted and multiplied with each other. Each matrix will be accessible with a few button presses.

    Should I create a certain number of pointers, say 5 or 10 (the # would be the maximum # of matrices the user can use)?

    Then whenever the user creates a new matrix, do this?

    Code:
    matrix *p;
    
    p = new matrix;
    I think this would work, correct? But the only problem with it is that it would require lots of repetitive code, since I'd have to write a statement like the one above for every pointer. And would it waste memory if not all the pointers are used?

    Is there a more elegant way of doing it?
    Last edited by Captain Penguin; 09-13-2002 at 01:43 PM.

  8. #8
    Registered User
    Join Date
    Aug 2002
    Posts
    57
    Yeah I was about to say something like that because I saw a disturbing error with the code.

    Code:
    Object *newObject;
    newObject= new Object
    
    // do stuff
    
    delete newObject;
    newObject= NULL;
    "A Programmer being told to 'go to' hell sees the 'go to' part of the sentence as the worst part." - Master Foto

  9. #9
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    I'm not sure what Alphabird thought was wrong with the code that he posted, but anyway, I have the solution to your problem.

    Create a linked list which has a pointer and the name of each of your dynamically allocated matrixes. Dynamically allocate the nodes of the linked list. Problem solved...NEXT!
    Away.

  10. #10
    Registered User
    Join Date
    Aug 2001
    Posts
    244
    Originally posted by blackrat364
    I'm not sure what Alphabird thought was wrong with the code that he posted, but anyway, I have the solution to your problem.

    Create a linked list which has a pointer and the name of each of your dynamically allocated matrixes. Dynamically allocate the nodes of the linked list. Problem solved...NEXT!
    I think the problem was that the object wasn't set to NULL?

    Anyways.. linked lists? nodes?

    Hmm... havn't learned about linked lists as of yet. Can you provide a link that explains? Also, what should I know beforehand? (I know alll about pointers, classes, arrays, references.. basically upto day 10 in "Teach yourself C++ in 21 days")

  11. #11
    Pursuing knowledge confuted's Avatar
    Join Date
    Jun 2002
    Posts
    1,916
    ah, well, I'll just explain linked lists really fast. With an example, even.
    Code:
    class matrix;
    class linkedlist;
    
    //you would want to add member functions to this class to go to the next node and add new nodes, etc, but I'm being lazy right now.  You would also want a constructor to set those pointers to null.
    class linkedlist
    {
         public:
           matrix *thematrix;
           char name[8];
           linkedlist *nextnode;
    }
    
    int main()
    {
         linkedlist headnode;
         linkedlist *lastnode;
    
         lastnode=&headnode;
         
         linkedlist.nextnode=NULL;
         linkedlist.thematrix=new matrix;
         linkedlist.name="mtrxtwo";
         
         if (needtoaddanothermatrix)
         {
              //create a new node, made lastnode point to the node just created, create a new matrix to go in the new node
              lastnode->nextnode=new linkedlist;
              lastnode = lastnode->nextnode;
              lastnode->thematrix = new matrix;
              lastnode->nextnode=NULL;
         }
    }
    That code is hardly sufficient for doing anything, for one thing, you've got a great big memory leak...you have to negotiate your entire linked list, starting at headnode, and use the delete keyword to delete the matrix in each node AND all of the nodes. That would be much easier with destructors for the linked list class.

    The basic theory behind a linked list is a structure which contains a pointer to the next item in the structure, so the list can grow or shrink in run time, dynamically allocated. Thought I should throw that in.

    If you still have questions, ask, or just do a board search or a search on google for "linked lists."
    Away.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Following CTools
    By EstateMatt in forum C Programming
    Replies: 5
    Last Post: 06-26-2008, 10:10 AM
  2. Style Points
    By jason_m in forum C Programming
    Replies: 4
    Last Post: 05-28-2008, 06:15 AM
  3. Creating array of objects w/o default constructor
    By QuestionC in forum C++ Programming
    Replies: 19
    Last Post: 05-02-2007, 08:03 PM
  4. creating a struct based on user input
    By rodrigorules in forum C Programming
    Replies: 1
    Last Post: 09-15-2005, 06:16 PM
  5. Creating a user account...
    By xiao guang in forum Tech Board
    Replies: 2
    Last Post: 07-14-2003, 06:49 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21