GP32 Could Somebody Explain These C++ Concepts To Me?


Dalto posted on Aug 7 2004 at 05:34 PM said:
I went there and it doesn't seem to help. It seems to be a guide for C, first of all. And it confused me a bit when it said "struct node." So, I just decided to not bother with it for now (It kept going on with struct node, I don't know WTF that is. Is struct a type or something?).
 
Last edited by a moderator:
Azure posted on Aug 8 2004 at 06:22 AM said:
Dalto posted on Aug 7 2004 at 05:34 PM said:
I went there and it doesn't seem to help. It seems to be a guide for C, first of all. And it confused me a bit when it said "struct node." So, I just decided to not bother with it for now (It kept going on with struct node, I don't know WTF that is. Is struct a type or something?).
Structs(as I can better reply by showing you what someone else posted on a different message board). Are classes with:

No inheritence
No control of access using private, protected, or public keywords
No member functions
No operator functions
No friends (in C everything is a friend of a struct by default)
No constructors or destructors
 
Last edited by a moderator:
I'm having a hard time learning how to use linked lists. I don't know their syntax too well. Here's my code:
Code:
//
//
//
//
//
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
using namespace std;

class account
{
    public:
        double balance;
        string name;
        static int numberofaccounts;
        account (string accountname)
        {
            cout << "Constructing account...";
            cout << "\nAccount constructed.";
            name = accountname;
            numberofaccounts++;
            balance = 0;
        }
        ~account ()
        {
            cout << "Destructing accounts...";
        }
            
        void currentbalance ()
        {
            cout << "Your current balance is " << balance << ". \n";
        }    
        
        void deposit ()
        {
            int depositcorrect = 1;
            int depositquit = 1; 
            double depositamount = 0;
            cout << "\nYou have selected the deposit function.";
                
            for (;;)
            {
                cout << "\nPlease enter in the amount you wish to deposit: ";
                cin >> depositamount;
                cout << "\nYou entered " << depositamount;
                cout << "\nIf this is correct, enter 1, if not enter 2.";
                cout << "\nEnter in any number other than 1 or 2 to exit the deposit function.\n";
                cin >> depositcorrect;
                
                if (depositcorrect < 1 || depositcorrect > 2)
                {
                    cout << "\nNow exiting the deposit funcion...";
                    break;
                } 
                
                if (depositcorrect == 1)
                {     
                    balance += depositamount;
                    cout << "\nYou have just deposited " << depositamount << " dollars into your account.";
                    cout << "\nYou're current balance now is " << balance << ".";
                    cout << "\nEnter 1 to make another deposit, otherwise, enter any other number to\nexit this function.\n";
                    cin >> depositquit;
                    if (depositquit != 1)
                    {
                        break;
                    }
                }
                
                if (depositcorrect == 2)
                {
                    cout << "\nYou have chosen 2, in that the deposit amount enter is incorrect.";
                }
            }
        }
        
        double withdraw ()
        {
            double withdrawlamount = 0;
            int withdrawlcorrect = 1;
            int withdrawlquit = 1;
            cout << "\nYou have selected the withdrawl function.";
                
            for (;;)
            {
                cout << "\nPlease enter in the amount you with to withdraw: ";
                cin >> withdrawlamount;
                cout << "\nYou entered " << withdrawlamount;
                cout << "\nIf this is correct, enter 1, if not, enter 2.";
                cout << "\nEnter in any number other than 1 or 2 to exit the withdrawl function.\n";
                cin >> withdrawlcorrect;
                
                if (withdrawlcorrect < 1 || withdrawlcorrect > 2)
                {
                    cout << "\nNow exiting the withdrawl function...";
                    break;
                }
                
                if (withdrawlcorrect == 2)
                {
                    cout << "\nYou have chosen 2, in that the deposit amount enter is incorrect.";
                }
                
                if (withdrawlcorrect == 1)
                {
                    balance -= withdrawlamount;
                    cout << "\nYou have just withdrawn " << withdrawlamount << " dollars from your account.";
                    cout << "\nYour current balance now is " << balance << ".";
                    cout << "\nEnter 1 to make another withdrawl, otherwise, enter any other number to exit\nthis function\n";
                    return withdrawlamount;
                }
            }
        }
};
                
int account::numberofaccounts=0;

int main (int nNumberofArgs, char* pszArgs[])
{
    double deposit;
    double withdrawl;
    double cash;
    char choice;
    
    string accountname;
    
    cout << "\nEnter in the name of the account you would like to create: ";
    cin >> accountname;
    account account1(accountname);
    
    cout << "\nEnter 'd' to deposit money into your account.";
    cout << "\nEnter 'w' to withdraw money from your account.";
    cout << "\nEnter 'b' to view your accont's balance.\n";
    cin >> choice;
    
    switch (choice)
    {
        case 'd':
        account1.deposit();
        break;
        
        case 'w':
        cash = account1.withdraw();
        break;
        
        case 'b':
        account1.currentbalance();
        break;
    }
    
    system ("Pause");
    return 0;
}
I want to add a linked lists that keeps track of all the deposits made. How would I go about doing this? I've read how linked lists worked a lot from lots of different sources by now, but that means nothing if I don't know their syntax and how to actualy write them. So, could somebody give me the code for the linked list?

Here's how I think it would work:
Code:
class LinkableClass
{
    public:
        LinkableClass* pNext;
        LinkableClass* pHead;
        LinkableClass* pTail;
        LinkableClass* pL; 
        
        void add (despositamount)
        {
            pL = pL->pHead; // points to the head of the list
            pL = depositamount; //pL points to depositamount to the head of the list
            pL = pL->pNext; //pL points to the next item in the list
        }
}
Then, after the deposit is made, I would do depositamount = pL. Is this code right? If not, what's wrong with it? What I don't udnerstand with it is, if it's going to constantly add items to the list, won't it add a deposit to the head, then the next time around add it to the next node, then add it to the head again? How would I make it add it to the head once, then add it to the next node from thereafter?
 
Thanks! Now that I have an example, can you explain to me how the linked list works in my program now (Explaining it one step at a time)?

I also some strange syntax:
(The text before the code: "Just as with member objects, you often need to be able to pass arguments to the base class constructor. The example program declares the subclass constructor as follows:
Code:
class GraduateStudent : public Student
{
    public:
GraduateStudent(char *pName, Advisor& adv, float qG = 0.0)
                [b]: Student(pName), advisor(adv), qualifierGrade(qG)[/b]
{
        // whatever construction code goes here
}

float qualifier( ) {  return qualifierGrade;  )

protected:
     [b]Advisor advisor;[/b]
     float qualifierGrade;
};
So, what the heck is the fifth line of code? What does that mean? Also, what's up with the protected member, "Advisor advisor?" Is Advisor a type?

I also am having a hard time with pointers and references (Before I saw them used in simple cases but now I question the need of them in examples in my book). Here's an example image:
pointer1.jpg

What I don't understand is, why does the pHeadObject have to be a pointer an object of class Base? Also, what about the line that reads "delete pHeadObject?" This actually invokes the destructor? The "delete" command is supposed to invoke the destructor? Here's another one:
pointer2.jpg

Any particular reason why one would want the return type of the makeACopy() function to be a pointer?
So, when would you use a pointer in an argument and when would you use a reference to an object in an argument (Everytime because if you don't a copy will be made?)?

Here's the last one for this pointer thing I'm confused about:
pointarg.jpg

(It's actually two pictures combined, showing all of the code)
For this one, I don't understand the arguments in the Student constructor. How can you have an "=" in an argument? When the student object is created later in the code, all it says in the () is "'Chester,'" how would this be passed to a function when it's argument is "char* pN = "no name?" And lastly, why does pName have to be a pointer in this code? Why can't it just be a normal char?
 

Attachments

  • pointer1.jpg
    pointer1.jpg
    27.4 KB · Views: 159
  • pointer2.jpg
    pointer2.jpg
    23.5 KB · Views: 167
  • pointarg.jpg
    pointarg.jpg
    53.2 KB · Views: 181
  • pointer1.jpg
    pointer1.jpg
    27.4 KB · Views: 171
  • pointer2.jpg
    pointer2.jpg
    23.5 KB · Views: 163
  • pointarg.jpg
    pointarg.jpg
    53.2 KB · Views: 175
  • pointer1.jpg
    pointer1.jpg
    27.4 KB · Views: 163
  • pointer2.jpg
    pointer2.jpg
    23.5 KB · Views: 166
  • pointarg.jpg
    pointarg.jpg
    53.2 KB · Views: 165
Thought I would "bump" because I edited my post sometime after I posted it with these other concepts, and I think everybody just read my original post and didn't see my edit.
 
For this one, I don't understand the arguments in the Student constructor. How can you have an "=" in an argument? When the student object is created later in the code, all it says in the () is "'Chester'" how would this be passed to a function when it's argument is "char* pN = "no name?" And lastly, why does pName have to be a pointer in this code? Why can't it just be a normal char?

If there is an = in an argument it means that if you want, you can call the function without passing in a value and it will be as though you are passing in the value after the = sign.

"Chester" is passed in as it is a string which can be stored as a pointer to some letters (char*) and will be what pN becomes equal to in the function code. As the function has a value passed in, it overrides the default value (after the = sign).

A normal char can only hold 1 letter (it actually can hold a number from -128 to 127 which represents an ASCII code for a letter - if you search on the web or perhaps in your book you will find a table that tells you what numbers represent what characters). A char* (like any pointer) is actually a 32 bit number that represents a position in the computers memory from 0 to 4294967295 (this is enough locations for 4GB of RAM if you were wondering). The computer knows what type of data to expect in that memory position due to the type of variable before the * in your case it is expecting an 8 bit number (a char) which actually takes up a single location. For reference a short takes up 2 locations (16 bits) and an int takes up 4 locations (32 bits), as does a float.

To access the data in the memory position represented by the char* pN you can either use *pN or pN[0]. Think of it as *pN is acessing exactly where it is 'pointing' to (the memory location), pN[0] is acessing 0 memory positions after the position stored in pN, and changing pN with no * and no [] will change the memory location it is pointing to. IE pN = 1000; will make the variable point to the 1000th memory position of the computer, *pN = 10; will change the 1000th memory position to hold a value of 10 and pN[0] += 5; will add 5 to the value stored in the 1000th memory location (in this case making 15).

Thus if you wanted to hold more than a single character in memory you will need to use more than 1 memory location (remember 1 memory location = 8bits = 1 byte = char). So what you do is use a char * pN; Where as previously described, pN is a memory location. pN[0] is the 1st letter pN[1] is the memory location held (pointed to) by pN + 1 and thus can be the second letter, pN[2] is the 3rd letter and so on..... say you wanted to store the word Chester in memory. pN[0] would equal C, pN[1] would equal h ... and pN[6] would equal r. Note that the memory position after the last letter (in this case pN[7]) should always equal 0.

Hope this helps... I'm off to bed.
 
Hmm...then why not have pN be a char array instead? I also need help with the other two pointer ones and the first one about the ":" in the the class constructor.
 
Oh yeah, could someone also explain to me how porting works (What exactly do you do to the source code)?
 
I was under the impression that porting was adapting the source to use the gp32 or mirkos sdk rather than it's origionals. So all the basic code is still there but it just uses different input/output commands so that you can interact with it on the gp.
 
Azure posted on Aug 14 2004 at 09:36 PM said:
Oh yeah, could someone also explain to me how porting works (What exactly do you do to the source code)?
That depends on what your porting.

At the very least you will have to change all the routines that write to the screen to use the gp32 specific functions.

Any assembly will have to be rewritten.

You have to remove multithreading.

You have to make it run in 8MB of RAM.

You have to rewrite the sections that write to the disk to work with an SMC.

These are just some examples. Some things will port over very easily and others will require a lot of modifications.
 
Last edited by a moderator:
After reading some of your previous posts, I think you are basically asking:

Why do we pass in and out pointers sometimes, whereas other time we pass in and out normal variable?

Whenever you pass any type of variable into a function, be it a pointer, a class or a normal variable, the function you pass it to never gets the original, it just gets a copy which gets destroyed at the end of the function. For example :

Code:
void main()
{
   int nTest = 10;

   ExampleFunction(nTest);

  cout << nTest;
}

void ExampleFunction(int nInput)
{
   nInput += 10;
}

In the preceding example, the nTest variable that gets outputted to the screen at the end of main() equals its original value of 10, even though it was passed into ExampleFunction, which adds 10 to it. This is because ExampleFunction works with a copy of nTest, adds 10 to it, which then it gets forgotten at the end of ExampleFunction. However, if you have the following situation:

Code:
void main()
{
   int nTest = 10;

   ExampleFunction(&nTest);

  cout << nTest;
}

void ExampleFunction(int* pnInput)
{
   *pnInput += 10;
}

In the preceding example, ExampleFunction now takes in a pointer to an integer. Remember in my previous post I explained that pointers just hold a 32 bit (8 byte) number representing a position in memory? Well, that is what ExampleFunction expects to be given, a position in memory. In the main() function nTest is declared as an integer equaling 10, but we don't want to pass that to the ExampleFunction any more. We need to pass it's memory location and that is why we use the & sign. If you cout << &nTest, it will give you a number other than 10, this number is the nTest's memory location (effectively a pointer to an int).

This memory location is passed into ExampleFunction(int* pnInput), which does not use the original memory location number, but makes a copy of it. This copy is still the same value as &nTest. Thus when we edit the data which is held in the copy of the memory location we are actually editing the nTest variable. The copy of the memory location is forgotten/destroyed at the end of the ExampleFunction.

cout << nTest; will now print out 20

So using the above logic, if you pass in a pointer to a class object you have created, you are just giving the function the memory address of your class object. The function may use this memory location to access the class object that is being used in your main program, thus editing any values of the class stored in the given memory location or even destroying it will actually effect the object in your main program. If you don't pass it in as a pointer variable, you are making the function copy all the data in your class object which it will then edit. Anything you edit will not effect the original object in your main program. When the function finishes, the created copy will be destroyed.

As well as being pointless, it can be slower to pass data into a function without passing it in as a pointer. This is because a pointer (on a 32 bit machine) will always be 32 bits (8 bytes) in size. This is the size of an int or a float, quite small and quick to copy and destroy. If you pass in a class, it could be a lot of data that needs to be copied, thus taking more time and more memory.

Bed time for me.....
 
In that second code example, why isn't the arguement to the function int &pnInput? It's getting passed the address of an int, not a pointer to an int, is it not? Also, I still need help with this one:
Azure said:
I also some strange syntax:
(The text before the code: "Just as with member objects, you often need to be able to pass arguments to the base class constructor. The example program declares the subclass constructor as follows:
CODE

class GraduateStudent : public Student
{
public:
GraduateStudent(char *pName, Advisor& adv, float qG = 0.0)
: Student(pName), advisor(adv), qualifierGrade(qG)
{
// whatever construction code goes here
}

float qualifier( ) { return qualifierGrade; )

protected:
Advisor advisor;
float qualifierGrade;
};

So, what the heck is the fifth line of code? What does that mean? Also, what's up with the protected member, "Advisor advisor?" Is Advisor a type?
 
Last edited by a moderator:
Azure said:
In that second code example, why isn't the arguement to the function int &pnInput? It's getting passed the address of an int, not a pointer to an int, is it not?
That is a different way of doing pass by reference. The one more commonly used in C. If you scroll back up a ways you should find me explaining the two different ways you can do pass by reference in C++.

Azure said:
So, what the heck is the fifth line of code? What does that mean? Also, what's up with the protected member, "Advisor advisor?" Is Advisor a type?
OK, the fourth and fifth line of code are actually one statement broken into two lines for ease of formatting. If you go WAAY back in this thread you should find some stuf like this early on. Variables inside classes cannot be initialized. They need to be initialized by the constructor itself. That's what this does.

It calls the base classes constructor and the constructors for the two class variables.

Advisor is a class, probably declared on one of the preceding pages.
 
Last edited by a moderator:
Dalto posted on Aug 17 2004 at 01:51 PM said:
Azure said:
In that second code example, why isn't the arguement to the function int &pnInput? It's getting passed the address of an int, not a pointer to an int, is it not?
That is a different way of doing pass by reference. The one more commonly used in C. If you scroll back up a ways you should find me explaining the two different ways you can do pass by reference in C++.

Azure said:
So, what the heck is the fifth line of code? What does that mean? Also, what's up with the protected member, "Advisor advisor?" Is Advisor a type?
OK, the fourth and fifth line of code are actually one statement broken into two lines for ease of formatting. If you go WAAY back in this thread you should find some stuf like this early on. Variables inside classes cannot be initialized. They need to be initialized by the constructor itself. That's what this does.

It calls the base classes constructor and the constructors for the two class variables.

Advisor is a class, probably declared on one of the preceding pages.
So it's to ensure that when the Graduate Student object is create, so is the object from which it inherits?
 
Last edited by a moderator:
In reply to Dalto's code.. I had a go at explaining it.. (bear in mind that my knowledge of LL is nt great either)
Code:
/*I wont pretend to understand all of this code as I do my linked lists differently but I have
the gist of it. I have isolated the most important parts that are relevent to the linked lists.
You may also want to look at vectors from the STL.*/
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string.h>
using namespace std;
 
class LinkableClass
{
   // This class basically makes dynamic iterations of itself all connected via pointers
   // using the 'new' function. 
   // eg
   // node1
   // node1's pHead points to node1 and node1's pNext points to NULL
   // add another deposit
   // node1's pHead still points to node1 but node1's pNext now points to node2 and 
        // node2's pNext is now pointing to NULL and node2's pHead is now pointing to node1
        
   // diagram
        //pHead--> node1 --> node2 --> NULL
   public:
       LinkableClass* pNext;   // points to the next deposit entry in the list
       LinkableClass* pHead;   // points to the first deposit in the list... this rarely changes
                                //As far as the program is concerned it only needs to know where
                                // the head is and then it tranverses through the list by following
                                // the pointers of pNext within each node until it reaches the end
                                // ie when pNext is equal to NULL
       double depositamountdata;
 
       LinkableClass( LinkableClass *head, double depositamount )
       {
           pNext=NULL;    // make the pNext point to NULL/nothing
           if( head==NULL )  // if a list doesnt exist
            pHead=this;  // not sure about 'this' but I am guessing it means 'itself'
                        // if this is the first node that is created, there isnt a head pointer
                        // that it can copy so this makes the pHead point to the same node it belongs to
           else
            pHead=head;  // else make it point to the head
           depositamountdata=depositamount;
       }
       //eg
       /*
                     -----------------<----------------[NODE2.pHead]
                     |                                       |
               --> NODE1 --------[NODE1.pNext]-----------> NODE2 --------[NODE2.pNext]-------> NULL
               |     |
               -[NODE1.pHead]

       */
 
       LinkableClass* add( double depositamount )
       {
           this->pNext=new LinkableClass(this->pHead, depositamount); // call the above function whilst making/passing
                                                                        // a new instance of LinkableClass whislt making
                                                                        // the current nodes pNext pointer point to it
           return this->pNext;
       }
};
 
class account
{
    public:
        void OutputDepositHistory( void ) // ie transverse throught the list starting from the head
                                            // and print out all the data whilst working through the list
        {
          if( curNode == NULL )  // if the list is empty then exit function
            return;
 
          curNode=curNode->pHead; // make the current pointer point to the address of the head of
                                    // the list
          do
          {
            cout << curNode->depositamountdata << "\n";  // output the deposit
            curNode=curNode->pNext; // make the current pointer pointer to the same place as the current
                                    // node's pNext pointer (next in the list)
          } while( curNode != NULL ); // do while the pNext of the current node is not pointing to NULL
          return;
        }
};
 
Back
Top