Hello Guest, please login or register.
Did you miss your activation email?
Login with username, password and session length.

Pages: [1]   Go Down

Author Topic: [Request / Solved] A Lot of C++ Questions  (Read 2191 times)

0 Members and 1 Guest are viewing this topic.
[Request / Solved] A Lot of C++ Questions
« on: June 08, 2006, 06:48:08 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
First, let me say thanks to aab and Helios for helping me with my learning C++. I appreciate it. Enough to repay you. At 7:00.

Ok, now onto the question(s).

1). Memory. Stack and heap. What code gets allocated in what? For example, if I just had a simple int main() and declared a variable, would it be in the stack or the heap? What are global variables in C++? Where do they get allocated?

example

Code: [Select]
int main() {
       int variable = 10;
       int *ptrToVar = &variable;
}
Where would the pointer get allocated to? Where would the regular variable get allocated to? The stack or the heap? When do things get allocated to the heap?

What is the point of dynamic memory allocation? Why must you use a pointer to do this? Exlain everything about this (my book did a sucky job of explaining this). For example, I know how to dynamically allocate

Code: [Select]
int main() {
   int *ptr = new int;
  //blah blah
   delete ptr;
   ptr = 0;
}
(And I just set the ptr to 0 just for safety).
Where does this get allocated, the stack or the heap? What would you use this for?

2). Classes

What is the point of making member funcitons and member variables public or private? If you don't want a user to call the function, just don't do it - I don't see the reason for having to make it private. Just like if there were a bridge, you wouldn't jump off, even if there weren't a gate stopping you from doing it.

Explaining everything about const, and why it works, how it works, please.

Why would you want a pointer to an instance? I don't get it. Explaining dynamic memory allocation with instances too, please. For example:

Code: [Select]
class Pen {
   public:
      int inkLevel;
      string brand;
      void break(int inkLevel);
       
}

void Pen::break(int inkLevel) {
      if(inkLevel > 0) {
           inkLevel /= 2;
     }
}
int main() {
     Pen *myPen = new pen;
     myPen->inkLevel
///blah blah
Please explaining everything about constructors and deconstructors.

If anyone knows of a website which explains how much memory each variable type takes up, that would help greatly.
« Last Edit: March 06, 2012, 07:32:03 pm by Niek »
Logged
Re: A Lot of C++ Questions
« Reply #1 on: June 08, 2006, 07:43:06 pm »
  • *
  • Reputation: +3/-0
  • Offline Offline
  • Gender: Male
  • Posts: 6629
1)
Memory = Whatever you wish to store, normally globals
Stack = Scope frames, local variables
Heap = Dynamically allcoated memory (class instances and so on)

As for pointers they are stored just like varaibles, in fact pointers are all 4 bytes long (integers)

2)
For private and public, just remember you may not be the only one working on the project. What happens if it goes open-source and some idiot trys to call an internal method?

Const, well put simply it maks things constant (ie, it can't be modified)

Construtors are automatically called when an instance of the object is created, same thing for destructors but it gets called when you delete the object.

As for memory of each variable
Int = 4 bytes (32 bits)
Int8 = 1 byte (8 bits) (also named byte and char)
Int16 = 2 bytes (16 bits) (also named short and word)
Int32 = Same as Int (also named dword)
Float = 4 bytes

If you need details on other variables just ask.


« Last Edit: June 08, 2006, 07:45:37 pm by Helios »
Logged
Re: A Lot of C++ Questions
« Reply #2 on: June 08, 2006, 09:43:00 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Ok,some more questions.

First, what are score frames? What are global/local variables - (I know what they are in Game Maker, not here though)? What gets stored on the stack and heap?

About public and private, that's what I thought.


What is the point of dynamic memory allocation? What is the point of using pointers? I don't see when I'd even HAVE to use them.

As for variable memory - I was wondering:

Int, signed and unsigned
float
double
char

ANd I was wondering what the difference between float and double is.

Thanks for the help.
Logged
Re: A Lot of C++ Questions
« Reply #3 on: June 08, 2006, 10:00:59 pm »
  • *
  • Reputation: +3/-0
  • Offline Offline
  • Gender: Male
  • Posts: 6629
Ok,some more questions.

First, what are score frames? What are global/local variables - (I know what they are in Game Maker, not here though)? What gets stored on the stack and heap?

About public and private, that's what I thought.


What is the point of dynamic memory allocation? What is the point of using pointers? I don't see when I'd even HAVE to use them.

As for variable memory - I was wondering:

Int, signed and unsigned
float
double
char

ANd I was wondering what the difference between float and double is.

Thanks for the help.

Stack frames = Seriously unless you want to knwo the internal workings of your CPU you don't need to know.
Global = As it says global to the whole program, usually declared in the global scope.
Local = Local to the scope its declared in can't be modified outside it.
Static = Almost the same as global but can be declared inside a function and will not loss its value when you exit the functions scope.

DMA and pointers are highly important, without them you really can't do anything at all, you couldnt even create class instance <_<.

A float is accurate to within 8 decimal places, a double is litterally double that.

Int, signed and unsigned = One can be negative the other cant.
float = 4 bytes, means floating-point variable, basically a real in GML terms.
double = Same as float but doubbly as accurae.
char = 1 byte, used normally to store a character. Can hold a value between 0 and 255.
Logged
Re: A Lot of C++ Questions
« Reply #4 on: June 08, 2006, 10:14:30 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Stack frames = Seriously unless you want to knwo the internal workings of your CPU you don't need to know.

I do.

You can create a class though without DMA. Look:

Code: [Select]
class Car {
   public:
        for(int i = 0; i < 4; i++) {
               bool flatTire[i] = false;
        }
        int gasGallons;
};

int main() {
    Car Honda;
    Honda.gasGallons = 20;
    Honda.flatTire[2] = true;
}

etc.

Thanks for the variable info tho.
Logged
Re: A Lot of C++ Questions
« Reply #5 on: June 08, 2006, 10:18:10 pm »
  • *
  • Reputation: +3/-0
  • Offline Offline
  • Gender: Male
  • Posts: 6629

You can create a class though without DMA. Look:

Code: [Select]
class Car {
   public:
        for(int i = 0; i < 4; i++) {
               bool flatTire[i] = false;
        }
        int gasGallons;
};

int main() {
    Car Honda;
    Honda.gasGallons = 20;
    Honda.flatTire[2] = true;
}

etc.

Thanks for the variable info tho.
Lol, that has so many errors i just dont want to go into it XD.

Quote
Stack frames = Seriously unless you want to knwo the internal workings of your CPU you don't need to know.

I do.
Ok stack frames are the way in which the stack and CPU stores details of the return address and local variables of a function (or other scope) when its called, without this the stack would be impossible to use. This feature is there to allow recursive function calls among other things, as if local variables were staticly assigned you would have the same value for every recursive function call, precisly what you dont want, so there dynamically allocated onto the stack frame.


Logged

gm112

Re: A Lot of C++ Questions
« Reply #6 on: June 08, 2006, 10:24:38 pm »
I would be the idiot to call a internal method
Logged
Re: A Lot of C++ Questions
« Reply #7 on: June 09, 2006, 12:07:56 am »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Lol, that has so many errors i just dont want to go into it XD.

I know, lol. But you hopefully know what I was trying to say. You could create a class without DMA. Can you not?

Here's what I mean:

Code: [Select]
class Pen {
   public:
      int inkamount;
      string color;
};
So, now you have a class called "Pen". You can make an instance non DMA or with DMA. What is the difference (memory wise - aka on the stack or heap), and why is one better than the other? What would be the point of doing one over the other, and what are uses of each way of making it? for example;

non-DMA

Code: [Select]
Pen myPen;
myPen.ink = 20;
myPen.color = "Blue";

OR

Code: [Select]
Pen *myPen = new Pen;
myPen -> ink = 20;
myPen -> color = "Blue";
« Last Edit: June 09, 2006, 01:20:15 am by Scooternew »
Logged

aab

^ Evolved from a Hobbit
Re: A Lot of C++ Questions
« Reply #8 on: June 09, 2006, 01:53:45 am »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 992
DMA.

Consider where you dont know how many of an object you will have at compile time.
You can create a variable number of objects, such as enemies, zfgc members, entrants to a swimsuit competition.
eg: With an array, the amount must be know at compile time: int zfgcKarma[NUM_ZFGCERS];
Allocate dynamically, and: int *zfgcKarma = new int [numZfgcers] ;, viola, the program to...say..sort all the zfgc-ers into order of karma doesnt need to be recompiled every time someone new joins or gets banned. Just run it again and read the value from a file.

There are also ways of having lists of objects, such as a list of enemies, where you can add a new enemy onto the list by allocating it dynamically, and free the allocated space of an enemy that has just died for example.

non DMA => stack
DMA => heap.


So, we need to dynamically allocate things at times, because we dont know how many or even if any will be in the program.
But, considering that we have to be carefull with pointers, eg:
int*p= 0;
...
 *p = 5; //runtime error ... program termination would be a good thing!
We need to have private spaces so that classes can manage their pointers and dynamically allocated data, withought some user of the class going instance.p = 0; so that next time he calls a class method, it crashes!
The Constructor can be used by that class to make sure its in a 'valid' state when starting, and the deconstructor can be used to deallocate.

If a class is incredibly safe, then a user using that class can be guaranteed that if their program doesnt work, it isnt because of them passing bad input or using the class imporperly, but rather something wrong with their actual code.
Of course, making something incredibly safe involves checks andd structures which might reduce compatibility and speed, and increase program size. Development time, costs, frustrations etc, go way down though ... And theres also an easier, more modular nature to when ensuring that the entire system has been appropriately tested.



Its also integral to various command patterns that i cant possibly mention to you at this stage.
Logged




I ♥ Sol
.... I ♥ Sol ? wtf how long has that been there? >_> *rrrrrrrrar*
  • MySpace
Re: A Lot of C++ Questions
« Reply #9 on: June 09, 2006, 02:59:46 am »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Thanks. That helped. Somewhat.

Quote
Consider where you dont know how many of an object you will have at compile time.
Why wouldn't you know? Say

Pen myPen;

That creates one pen. So you know how many pen you created. One. I'm not the "not knowing how many".
Logged
Re: A Lot of C++ Questions
« Reply #10 on: June 09, 2006, 10:53:37 am »
  • *
  • Reputation: +3/-0
  • Offline Offline
  • Gender: Male
  • Posts: 6629
Thanks. That helped. Somewhat.

Quote
Consider where you dont know how many of an object you will have at compile time.
Why wouldn't you know? Say

Pen myPen;

That creates one pen. So you know how many pen you created. One. I'm not the "not knowing how many".

Just get programming you'll understand why. What happens if you have a particle system? Your definatly not going to know how many particles that emits at runtime.

Hell, What happens if you have a game say space invaders, you dont wish to have a varaible for every ship as that would quite litterally be awfull

Code: [Select]
SpaceInvader Invader1;
SpaceInvader Invader2;
SpaceInvader Invader3;
SpaceInvader Invader4;
SpaceInvader Invader5;
SpaceInvader Invader6;
SpaceInvader Invader7;
SpaceInvader Invader8;
SpaceInvader Invader9;
SpaceInvader Invader10;
SpaceInvader Invader11;
SpaceInvader Invader12;
SpaceInvader Invader13;
SpaceInvader Invader14;
SpaceInvader Invader15;
SpaceInvader Invader16;
SpaceInvader Invader17;
SpaceInvader Invader18;
SpaceInvader Invader19;
SpaceInvader Invader20;
SpaceInvader Invader21;
SpaceInvader Invader22;
SpaceInvader Invader23;
SpaceInvader Invader24;
SpaceInvader Invader25;
SpaceInvader Invader26;
SpaceInvader Invader27;
SpaceInvader Invader28;
SpaceInvader Invader29;
SpaceInvader Invader30;

See? Where as with DMA...
Code: [Select]
SpaceInvader * Invaders = new SpaceInvader[30]
for(int i = 0; i <= 30; i++) {
    Invaders[i] = new SpaceInvader;
}

Simply put without DMA your code would look awfull, be bloated and completly unmanagable. You wouldn't even be able to create a linked list, as that requires the DMA of nodes, so you would end up having to do something like...

Code: [Select]
Invader1.Update();
Invader2.Update();
Invader3.Update();
Invader4.Update();
Invader5.Update();
Invader6.Update();
Invader7.Update();
Invader8.Update();
Invader9.Update();
Invader10.Update();
Invader11.Update();
Invader12.Update();
Invader13.Update();
Invader14.Update();
Invader15.Update();
Invader16.Update();
Invader17.Update();
Invader18.Update();
Invader19.Update();
Invader20.Update();
Invader21.Update();
Invader22.Update();
Invader23.Update();
Invader24.Update();
Invader25.Update();
Invader26.Update();
Invader27.Update();
Invader28.Update();
Invader29.Update();
Invader30.Update();

Where as with DMA and a linked list you could add all your objects to the list and mearly do this to update them.
Code: [Select]
ListNode * Node = List.head;
While(Node) {
    ((SpaceInvader)(Node.value)).Update();
    Node = Node.next;
}

and you can add or delete nodes at runtime
Code: [Select]
SpaceInvader * Invader = new SpaceInvader;
List.AddNode(Invader);
List.Remove(Invader);

...etc...etc...etc

simply put without DMA your going to have a unsable game, hell even GM used DMA even if its behinde the scenes, what do you think happens when you createa  new instance of an object in that.
Logged

aab

^ Evolved from a Hobbit
Re: A Lot of C++ Questions
« Reply #11 on: June 09, 2006, 03:37:50 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 992

Though its not the conceptual reason, i believe you can justify for yourself private class members by considering the risks and dangers associated with handling using the heap.
You can also instantly appreciate how usefull classes are, for example: Say you had an array but didnt know the size until runtime, during which it could change, you would be doing things like this:
Code: [Select]
int *items = 0;
. . .
items = new items[num_items];

/*Somwhere along, you realise you need to add another item:*/
/*copy array: note that i would never use the above code, nor even c equivelant with memcpy unless i was wanting platform independance to the extent of writing some code for a new age non embedded microwave oven processors compiler ..*/

++num_items;

int *copy = new items[num_items];

for( int t=0; t<num_items-1; ++t )
    // Make a copy of the allocation with one more element added
{
    copy[t] = items[t];
}


delete[]items;   //  delete old copy thats too small:

items = copy; //  now allow items to be used the same, only one more item.

Of course you dont want to write the above code all the time: Its risky and not the prettiest thing: Classes can wrap these kinds of things and make them easy to deal with.
For example, the standard template library already has a class to perform this kind o functionality: std::vector.
Code: [Select]
#include<vector>

...

std::vector< int > items;

items.push_back( 4 ); // 'array' now looks like so: { 4 }
items.push_back( 22 ); //array now looks like so: { 4, 22 }
items.push_back( 1 ); // .... { 4, 22, 1 }
items.resize( 5 );  //  { 4, 22, 1, ?, ? } ? as in dont know what that value would be: It would take on the value of whatever was previously at that variables position in the heap.

items [ 0 ] = 566;  //  { 566, 22, 1, ?, ? }
items[ 4 ] = -80;  //   { 566, 22, 1, ?, 80 }

items.pop_back(); // { 566, 22, 1, ? }

items.clear();   // {} ie empty.

Of course, then you might think that thats going to be doing alot of allocating and deallocating all the time, playing around with the heap more than you'd like. That does happen.

That is where linked containers come in (a container is an abstract data type ie class, that holds a number of objects and provides particular access and storage requirements: For example, vector stores them as a dynamic array, allows you to add and remove from the back and provides fast array like access).
With a list however (yes, theres <list> and std::list just like <vector> ), it stores information on where the variables are instead of reallocating like an array. So when you add a new object into the container, it can add it on/allocate it withought reallocating/changing the positions of the other values in the list.
To learn more about linked lists (no matter how far you have to leap, as long as your strong with pointer syntax, you migh just be ble to scrape past these concepts and learn a great deal), heres a tutorial which i learned (Had to look back into me old IE favourites lol)
http://www.gamedev.net/reference/articles/article2041.asp
Its more of a C style: In C++ you'd be wrapping that stuff in a class, but to work on it this way first is a fundamental educational step IMO.
Practicing making these things for yourself is very important, even though when working on a big project though, its better to rely on the tried and tested standard code.
DMA and writing a linked list was the first thing i done when i started C++.
I wrote all the code for each list explicitly, rather than making or using classes to do those things, so when i grew to appreciate classes and templates i could literally be excited :).

Heres an analogy that will get you thinking about DMA.

Say there was a Bitmap class.
You dont need DMA right? If you want one Bitmap, you just go:

Bitmap bitmap;
bitmap.load( "bitmap.bmp" ); //Note these classes dont actually exist lol.

Wrong, as youll have guessed before you read 'Wrong' just there, if anything ive said has made sense.
The bitmaps data itself MUST be dynamically allocated.
Can you imagine a world where the size of every bitmap used by a program must be known at compile time?

Say we had an object called a 'Pixel'
A bitmap needs width*height pixels: simple rectangles area calculation.

So, withion that Bitmap class, when you call 'load' it reads the bitmaps width, and reads its height, and then it MUST Go:
internalPixelArray = new Pixel [ width*height ];
There is absolutely no way you can deny that requirement.
Allocate an array for the size of the biggest posible bitmap you'd have and then store the number of pixels that you actually use? That would be disgusting in several ways: Use up far too much memory: involve lots of checks: severly limit the size of your bitmap.
You could even have a big array: a 'pool' of sorts, and 'allocate' from your pool, one bitmap to have space from index 0 to 400 and another space 400 to 700. But why would you want to deal with that when youve got a dynamic heap that deals with and equivelant system, result wise for you in a far more elegant manner?
Note that when i say 'result wise' i am not considering the time and efficiency, just that the same result is eventually obtained.
Obvious programming concept: If one method takes 10 times longer than the other, generally the choice is obvious as to which one to use (though for many many reasons its never that simple, even in a simple for loop).



Logged




I ♥ Sol
.... I ♥ Sol ? wtf how long has that been there? >_> *rrrrrrrrar*
  • MySpace
Re: A Lot of C++ Questions
« Reply #12 on: June 09, 2006, 04:18:08 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
That helped a LOT. Ok, I understand completely now, it works similarly in Game Maker. For example, if I had it so when you destroyed a sign, it needed to create a certain number of instances of an object, but I didn't know how many. It's similar to "instance_create" and "instance_destroy" in Game Maker.

New question. Is there a (can't remember the technical term) so that derived classes can inherit member variables but other users can't access them? Like private, but derived classes can ALSO inherit them.

Thanks for the help. I'm doing the best I can to learn.
Logged
Re: A Lot of C++ Questions
« Reply #13 on: June 09, 2006, 04:46:50 pm »
  • *
  • Reputation: +3/-0
  • Offline Offline
  • Gender: Male
  • Posts: 6629
protected?
Logged
Re: A Lot of C++ Questions
« Reply #14 on: June 09, 2006, 09:06:48 pm »
  • *
  • Reputation: +0/-0
  • Offline Offline
  • Gender: Male
  • Posts: 1635
Lol, that's the one. It worked.

Remember, I knew no C++ prior to about 6 days ago, so bear with me here. I'll post when I have a new question.
Logged
Pages: [1]   Go Up

 


Contact Us | Legal | Advertise Here
2013 © ZFGC, All Rights Reserved



Page created in 0.088 seconds with 65 queries.