The meaning of static in C++ - c++

I thought I was fairly good with C++, it turns out that I'm not. A previous question I asked: C++ const lvalue references had the following code in one of the answers:
#include <iostream>
using namespace std;
int& GenX(bool reset)
{
static int* x = new int;
*x = 100;
if (reset)
{
delete x;
x = new int;
*x = 200;
}
return *x;
}
class YStore
{
public:
YStore(int& x);
int& getX() { return my_x; }
private:
int& my_x;
};
YStore::YStore(int& x)
: my_x(x)
{
}
int main()
{
YStore Y(GenX(false));
cout << "X: " << Y.getX() << endl;
GenX(true); // side-effect in Y
cout << "X: " << Y.getX() << endl;
return 0;
}
The above code outputs X: 100, X:200. I do not understand why.
I played with it a bit, and added some more output, namely, a cout before the delete x; and a cout after the new x; within the reset control block.
What I got was:
before delete: 0x92ee018
after new: 0x92ee018
So, I figured that static was silently failing the update to x, and the second getX was playing with (after the delete) uninitialized memory; To test this, I added a x = 0; after the delete, before the new, and another cout to ensure that x was indeed reset to 0. It was.
So, what is going on here? How come the new returns the exact same block of memory that the previous delete supposedly free'd? Is this just because that's what the OS's memory manager decided to do, or is there something special about static that I'm missing?
Thank you!

That's just what the memory manager decided to do. If you think about it, it makes a lot of sense: You just freed an int, then you ask for an int again... why shouldn't the memory manager give you back the int you just freed?
More technically, what is probably happening when you delete is that the memory manager is appending the memory block you freed to the beginning of the free list. Then when you call new, the memory manager goes scanning through its free list and finds a suitably sized block at the very first entry.
For more information about dynamic memory allocation, see "Inside storage allocation".

To your first question:
X: 100, X:200. I do not understand why.
Since Y.my_x is just a reference to the static *x in GenX, this is exactly how it supposed it to be - both are referencing to the same address in memory, and when you change the content of *x, you get a side effect.

You are accessing the memory block that is deallocated. By the c++ standard, that is an undefined behaviour, therefore anything can happen.
EDIT
I guess I have to draw :
You allocate the memory for an int, and you pass the object allocated on the heap to the constructor of Y, which stores that in the reference
then you deallocate that memory, but your object Y still holds the reference to the deallocated object
then you access the Y object again, which holds an invalid reference, referencing deallocated object, and the result you got is the result of an undefined behaviour.
EDIT2
The answer to why : implementation defined. The compiler can create new object at any location it likes.

i test your code in VC2008, the output is X: 100, X: -17221323. I think the reason is that the static x is freed. i think my test is reasonable.

This makes perfect sense for the code.
Remember that it is your pointer that is static, so when you enter this function a second time you do not need to make a new pointer, but ever time you enter this function you are making a new int for the pointer to point to.
You are also probably in debug mode where a bit more time is spent giving you nice addresses.
Exactly why the int that your pointer points to is in the same space is probably just down to pure luck, that and you are not declaring any other variables before it so the same space in memory is still free

Related

How variable 'a' will exist without any object creation?

How variable int a is in existence without object creation? It is not of static type also.
#include <iostream>
using namespace std;
class Data
{
public:
int a;
void print() { cout << "a is " << a << endl; }
};
int main()
{
Data *cp;
int Data::*ptr = &Data::a;
cp->*ptr = 5;
cp->print();
}
Your code shows some undefined behavior, let's go through it:
Data *cp;
Creates a pointer on the stack, though, does not initialize it. On it's own not a problem, though, it should be initialized at some point. Right now, it can contain 0x0badc0de for all we know.
int Data::*ptr=&Data::a;
Nothing wrong with this, it simply creates a pointer to a member.
cp->*ptr=5;
Very dangerous code, you are now using cp without it being initialized. In the best case, this crashes your program. You are now assigning 5 to the memory pointed to by cp. As this was not initialized, you are writing somewhere in the memory space. This can include in the best case: memory you don't own, memory without write access. In both cases, your program can crash. In the worst case, this actually writes to memory that you do own, resulting in corruption of data.
cp->print();
Less dangerous, still undefined, so will read the memory. If you reach this statement, the memory is most likely allocated to your program and this will print 5.
It becomes worse
This program might actually just work, you might be able to execute it because your compiler has optimized it. It noticed you did a write, followed by a read, after which the memory is ignored. So, it could actually optimize your program to: cout << "a is "<< 5 <<endl;, which is totally defined.
So if this actually, for some unknown reason, would work, you have a bug in your program which in time will corrupt or crash your program.
Please write the following instead:
int main()
{
int stackStorage = 0;
Data *cp = &stackStorage;
int Data::*ptr=&Data::a;
cp->*ptr=5;
cp->print();
}
I'd like to add a bit more on the types used in this example.
int Data::*ptr=&Data::a;
For me, ptr is a pointer to int member of Data. Data::a is not an instance, so the address operator returns the offset of a in Data, typically 0.
cp->*ptr=5;
This dereferences cp, a pointer to Data, and applies the offset stored in ptr, namely 0, i.e., a;
So the two lines
int Data::*ptr=&Data::a;
cp->*ptr=5;
are just an obfuscated way of writing
cp->a = 5;

Null Pointers & Object Pointers

I was given instructions to show that a pointer variable can contain a pointer to a valid object, deleted object, null, or a random value. Set four pointer variables a,b,c, and d to show these possibilities. The the thing im not sure about are the pointer objects. Can someone explain what I need to do to show case these pointers. or if I did it right.
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
class Pointer
{
public:
Pointer()
{
int num = 2;
}
Pointer(int num)
{
this->numb = num;
}
void set(int num)
{
numb = num;
}
int Get()
{
return numb;
}
private:
int numb;
};
int main ()
{
Pointer point;
Pointer* a;
a = &point;
Pointer*b = new Pointer(10);
delete b;
int* c = NULL;
srand(unsigned(time(0)));
int randNum = rand()%100;
int *d;
d = &randNum;
cout <<"Pointer a: " << a << endl;
cout <<"Pointer b: " << b << endl;
cout <<"Pointer c: " << c << endl;
cout <<"Pointer d: " << *d << endl;
//(*a) = (*b);
return 0;
}
Not a complete answer, because this is homework, but here’s a hint: once you generate random bits (The C++ STL way to do this is with <random> and perhaps <chrono>), you can store them in a uintptr_t, an unsigned integer the same size as a pointer, and convert those bits to a pointer with reinterpret_cast<void*>(random_bits). The results are undefined behavior. Trying to dereference the pointer might crash the program, or it might appear to work and corrupt some other memory location, or it might do different things on different runs of the program, but nothing you do with it is guaranteed to work predictably. This is Very Bad.
If “random” really means arbitrary, for this assignment, you could just declare a pointer off the stack (that is, inside a function and not static) and not initialize it. Ask your instructor if you aren’t sure.
That’s a very common source of irreproducible bugs, and I would recommend you get into the habit now of always initializing your pointer variables when you declare them. Often, that lets you declare them int * const, which is good practice, but even if you need to wait to assign a real value to them, if you initialize your pointers to NULL or nullptr, you will always see immediately in the debugger that the value is uninitialized, and you will always crash the program if you try to use it uninitialized.
I would like to first point out what the word NULL means or nullptr, which is what you should be using in C++11. The null pointer just assigns the pointer to an inaccessible address or location in the memory. This allows for safer code, because the "dangling pointers" left over could be bad.
A header file and another cpp file to define the class
Class Something{
// Class implementation here
};
Now lets go to the main.cpp file
#include "The header you made.hpp" // (.h or .hpp)
int main(int argc, char *argv[]){
Something objOne;
Something *objPointer = &objOne;
// Do stuff with objPointer
// Like use your member functions
Something *objPointerTwo = &objOne;
// Now objPointerTwo points to the same object
// Lets try some runtime allocation of memory
Something *objHeap = new Something();
// Do something with the pointer
// Watch this
delete objHeap;
objHeap = nulltpr;
// Now what happens when you try to access methods again with objHeap
// Your program will display a segmentation fault error
// Which means you are trying to mess with memory
// that the compiler does not want you too
}
All right so what is this memory? Well to put it simply you have the heap and the stack. All the stuff you put into your program is put into the stack when it is compiled. So when the program runs the code follows main and traces the stack kind of like a stack of boxes. You may get need to search through all the top ones to get to the bottom. Now what if a person didn't know for example how many students were going to be in the class that year. Well the program is already running how do you make more room? This is where the heap comes in. The new keyword allows you to allocate memory at runtime, and you can "point" to memory on the "heap" if you will. Now while this is all good and cool, it can be potentially dangerous which is why people consider C++ and C dangerous languages. When you are done using that memory on the heap you have to "delete" it so when the pointer moves, the memory does not get lost and cause problems. It is kind of like a sneaky ninja and it goes and causes trouble.
A good way to think about how pointers can be good for objects is if you create say a deck class, well how many cards does the user want we wont know until runtime, so lets have them type in the number, and we can allocate it on the heap! Look Below
int main(void){
int count;
Deck *deck = nullptr;
std::cout << "Enter amount of cards please:";
std::cin >> count;
deck = new Deck(count); // RUNTIME ALLOCATION ON HEAP!!!!
// This is so cool right, you can have a deck of any size
// Do stuff with deck
// Now that we are done with the deck don't forget to delete it
// We do not need all those cards on the heap anymore so....
delete deck; // Ahhh almost done
deck = nullptr; // Just in case since dangling pointers are weird
}
The key thing to understand here is, what is a pointer, what is it pointing to, and how do they work with the memory!

pointer and dynamic memory allocation

My question:
int* x = new int;
cout << x<<"\n";
int* p;
cout << p <<"\n";
p = x;
delete p;
cout << p <<"\n";
I wrote this purely by myself to understand the pointer and to understand (also get lost in) the dynamic new and delete.
My XCode can compile the program and return the following results:
0x100104250
0x0
0x100104250
I know I can only call delete on dynamically allocated memory.
However, I called delete on p in the above program and it compiles.
Could anyone explain this to me?
Why could I delete p?
Moreover, I found if the program changes to the following:
int* x = new int;
int* p;
cout << p <<"\n";
delete p;
cout << p <<"\n";
Then my Xcode again compiles and returns me:
0x0
0x0
Program ended with exit code: 0
and now, I got completely lost:(.
Could anyone please explain me this ?
Why I could delete p since it has nothing to with x?
Since Xcode compiles successfully, I assume the above two programs are correct for computer.
However, I think it is again the statement of "only call delete on dynamic allocated memory".
Or probably, I didn't fully understand what is pointer and what is dynamic allocated memory.
I found this post when I searched online.
But I don't think it is like my case.
Please help me out.
I would like to ask one more question. The code is here about binary search tree.
From line 28 to 32, it deals with deleting a node with one child.
I put this part of code here, in case the weblink does not work.
else if(root->left == NULL) {
struct Node *temp = root;
root = root->right;
delete temp;
}
It is these codes leading me ask the above the question regarding pointer.
Following the answer given by this post.
Is it correct to understand the code in the following way?
I cannot firstly link the parent node of root to right child of root.
and then delete the root node, as the subtree beneath the root node will also be deleted.
So I must create a temp pointer, pointing to the memory slot, which is pointed to by root.
Then I link the parent node of root to right child of root.
and now, I can safely delete the memory slot pointed by "root", (i.e. temp as they both point to the same memory).
In this way, I release the memory and also keep the link between parent and children.
In addition, the temp is still there and still points to "that" memory slot.
Should I set it to NULL after deletion?
Thank you all again in advance.
Yaofeng
Yes, you can only call delete on memory which was allocated via new. Notice that it's the address of the memory (the value of the pointer) which matters, and not the variable storing the pointer. So, your first code:
int* x = new int; //(A)
cout << x<<"\n";
int* p;
cout << p <<"\n";
p = x; //(B)
delete p; //(C)
cout << p <<"\n"; //(D)
Line (A) allocates memory dynamically at some address (0x100104250 in your example output) and stores this address in variable x. The memory is allocated via new, which means that delete must eventually be called on address 0x100104250.
Line (B) assigns the address 0x100104250 (value of pointer x) into the pointer p. Line (C) then calls delete p, which means "deallocate the memory pointed to by p." This means it calls delete on address 0x100104250, and all is well. The memory at address 0x100104250 was allocated via new, and so is not correctly allocated via delete. The fact that you used a different variable for storing the value plays no role.
Line (D) just prints out the value of the pointer. delete acts on the memory to which a pointer points, not on the pointer itself. The value of the pointer stays the same - it still points to the same memory, that memory is just no longer allocated.
The second example is different - you're calling delete p when p was not initialised to anything. It points to a random piece of memory, so calling delete on it is of course illegal (technically, it has "Undefined Behaviour", and will most likely crash).
It seems that in your particular example, you're running a debug build and your compiler is "helpfully" initialising local variables to 0 if you don't initialise them yourself. So it actually causes your second example to not crash, since calling delete on a null pointer is valid (and does nothing). But the program actually has a bug, since local variables are normally not initialised implicitly.
p = x;
This would make p contain same value as x ( p would point to same object as x). So basically when you say
delete p;
Its doing delete on the address referred to by p which is same as that of x. Hence this is perfectly valid as object referred to by that address is allocated using new.
Second case :-
Co-incidently your pointer p is set by compiler as a NULL pointer( You should not depend on this). So deleting that pointer is safe. Had that not been a NULL pointer you would have possibly seen a crash.
Ok, let's take a look at the documentation for the "delete" operator. According to http://en.cppreference.com/w/cpp/memory/new/operator_delete:
Called by delete-expressions to deallocate storage previously allocated for a single object. The behavior of the standard library implementation of this function is undefined unless ptr is a null pointer or is a pointer previously obtained from the standard library implementation of operator new(size_t) or operator new(size_t, std::nothrow_t).
So what happens is the following: you are calling the new operator, which allocates sizeof(int) bytes for an int variable in memory. That part in memory is referenced by your pointer x. Then you create another pointer, p, which points to the same memory address. When you call delete, the memory is released. Both p and x still point to the same memory address, except that the value at that location is now garbage. To make this easier to understand, I modified your code as follows:
#include <iostream>
using namespace std;
int main() {
int * x = new int; // Allocate sizeof(int) bytes, which x references to
*x = 8; // Store an 8 at the newly created storage
cout << x << " " << *x << "\n"; // Shows the memory address x points to and "8". (e.g. 0x21f6010 8)
int * p; // Create a new pointer
p = x; // p points to the same memory location as x
cout << p << " " << *p << "\n"; // Shows the memory address p points to (the same as x) and "8".
delete p; // Release the allocated memory
cout << x << " " << p << " "
<< *x << " " << *p << "\n"; // p now points to the same memory address as before, except that it now contains garbage (e.g. 0x21f6010 0)
return 0;
}
After running, I got the following results:
0x215c010 8
0x215c010 8
0x215c010 0x215c010 0 0
So remember, by using delete you release the memory, but the pointer still points to the same address. That's why it's usually a safe practice to also set the pointer to NULL afterwards. Hope this makes a bit more sense now :-)
Before the answers, you need to understand the following points.
once you delete a pointer, it need not be assigned with 0. It
can be anything.
You can delete a 0 or NULL without any harm.
Undefined behavior is one in which anything could happen. The
program might crash, it might work properly as if nothing happened,
it might produce some random results, etc.,
However, I called delete on p in the above program and it compiles.
Could anyone explain this to me? Why could I delete p?
That is because you assign the address of memory allocated by new via x. ( p = x;) x ( or p) is a valid memory location and can be deleted.
Now x is called a Dangling pointer. Because it is pointing to a memory that no longer valid. Accessing x after deleting is undefined behavior.
Could anyone please explain me this ? Why I could delete p since it has nothing to with x?
This is because your p is assigned with 0. Hence you are getting away with undefined behavior. However it is not guaranteed that your uninitialized pointer will have a value of 0 or NULL. At this point it seems to work fine, but you are wading through undefined behavior here.
delete/free keyword is used to empty the stored value from the memory location. if we dont use pointers we have the reassign the value to NULL or just let them go out of scope.
Be careful using pointers, if we go out of scope using pointers without deleting the value. It will create memory leak. because that portion of the memory block is not usable anymore. And we lost the address because we are in different scope.

Why does this C++ code work? Stack memory and pointers

Here is some C++ code.
#include <iostream>
using namespace std;
class test{
int a;
public:
test(int b){
a = b;
cout << "test constructed with data " << b << endl;
}
void print(){
cout << "printing test: " << a << endl;
}
};
test * foo(){
test x(5);
return &x;
}
int main()
{
test* y = foo();
y->print();
return 0;
}
Here is its output:
test constructed with data 5
printing test: 5
My question: Why does the pointer to x still "work" outside of the context of function foo? As far as I understand, the function foo creates an instance of test and returns the address of that object.
After the function exits, the variable x is out of scope. I know that C++ isn't garbage collected- what happens to a variable when it goes out of scope? Why does the address returned in foo() still point to what seems like a valid object?
If I create an object in some scope, and want to use it in another, should I allocate it in the heap and return the pointer? If so, when/where would I delete it
Thanks
x is a local variable. After foo returns there's no guarantee that the memory on the stack that x resided in is either corrupt or intact. That's the nature of undefined behavior. Run a function before reading x and you'll see the danger of referencing a "dead" variable:
void nonsense(void)
{
int arr[1000] = {0};
}
int main()
{
test* y = foo();
nonsense();
y->print();
return 0;
}
Output on my machine:
test constructed with data 5
printing test: 0
When a variable goes out of scope, the destructor is called (for non POD data) and the location occupied by that variable is now considered unallocated, but the memory isn't actually written, so the old value remains. This doesn't mean that you can still safely access this value because it resides in a location marked as 'free'. New variables can reside or allocation can occur in this memory space.
The reason why the memory isn't erased is because you can't actually erase memory, what you could do is write something to it like all zeros or all ones or random, which is not only pointless, but performance-degrading.
It has nothing to do with garbage-collection. A garbage collector doesn't "erase" memory, but marks it as being free. The reason why the behaviour you described exists in C and not in Java for instance is not the garbage-collector, but the fact that C lets you access via pointers any memory you want, allocated or not, valid or not, and Java doesn't (To be fair the garbage collector is a reason why Java can make so that you can't access any memory).
An analogy can be made with what happens on disk when you delete a file. The file contents remain (they are not overwritten), but instead pointers (handles) in the file system are modified so that that memory on the disk is considered free. That's why special tools can recover deleted files: the information is still there until something new writes over it, and if you can point to it you can obtain it. Is almost the same thing with pointers in C. Think what would it mean to actually write 4GB on disk every time you delete a 4GB file. There is no need to write in memory for each variable that goes out of scope the entire size of that variable. You just mark it's free.

Why use pointers in C++?

I am learning C++ from a game development standpoint coming from long time development in C# not related to gaming, but am having a fairly difficult time grasping the concept/use of pointers and de-referencing. I have read the two chapters in my current classes textbook literally 3 times and even googled some different pages relating to them, but it doesn't seem to be coming together all that well.
I think I get this part:
#include <iostream>
int main()
{
int myValue = 5;
int* myPointer = nullptr;
std::cout << "My value: " << myValue << std::endl; // Returns value of 5.
std::cout << "My Pointer: " << &myValue << std::endl; // Returns some hex address.
myPointer = &myValue; // This would set it to the address of memory.
*myPointer = 10; // Essentially sets myValue to 10.
std::cout << "My value: " << myValue << std::endl; // Returns value of 10.
std::cout << "My Pointer: " << &myValue << std::endl; // Returns same hex address.
}
I think what I'm not getting is, why? Why not just say myValue = 5, then myValue = 10? What is the purpose in going through the added layer for another variable or pointer? Any helpful input, real life uses or links to some reading that would help make sense of this would be GREATLY appreciated!
The purpose of pointers is something you will not fully realize until you actually need them for the first time. The example you provide is a situation where pointers are not needed, but can be used. It is really just to show how they work. A pointer is a way to remember where memory is without having to copy around everything it points to. Read this tutorial because it may give you a different view than the class book does:
http://www.cplusplus.com/doc/tutorial/pointers/
Example: If you have an array of game entities defined like this:
std::vector<Entity*> entities;
And you have a Camera class that can "track" a particular Entity:
class Camera
{
private:
Entity *mTarget; //Entity to track
public:
void setTarget(Entity *target) { mTarget = target; }
}
In this case, the only way for a Camera to refer to an Entity is by the use of pointers.
entities.push_back(new Entity());
Camera camera;
camera.setTarget(entities.front());
Now whenever the position of the Entity changes in your game world, the Camera will automatically have access to the latest position when it renders to the screen. If you had instead not used a pointer to the Entity and passed a copy, you would have an outdated position to render the Camera.
TL;DR: pointers are useful when multiple places need access to the same information
In your example they aren't doing much, like you said it's just showing how they can be used. One thing pointers are used for is to connect nodes like in a tree. If you have a node structure like so...
struct myNode
{
myNode *next;
int someData;
};
You can create several nodes and link each one to the previous myNode's next member. You can do this without pointers, but the neat thing with pointers is because they are all linked together, when you pass around the myNode list you only need to pass the first (root) node.
The cool thing about pointers is that if two pointers are referencing the same memory address, any changes to the memory address are recognized by everything referencing that memory address. So if you did:
int a = 5; // set a to 5
int *b = &a; // tell b to point to a
int *c = b; // tell c to point to b (which points to a)
*b = 3; // set the value at 'a' to 3
cout << c << endl; // this would print '3' because c points to the same place as b
This has some practical uses. Consider you have a list of nodes linked together. The data in each node defines some sort of task that needs to be done that will be handled by some function. As new tasks are added to the list, they get appended to the end. Since the function has a pointer to the node list, as tasks are added on it receives those as well. On the other hand, the function can also remove tasks as it completes them, which are then reflected back across any other pointers that are looking at the node list.
Pointers are also used for dynamic memory. Say you want the user to enter in a series of numbers, and they tell you how many numbers they want to use. You could define an array of 100 elements to allow for up to 100 numbers, or you could use dynamic memory.
int count = 0;
cout << "How many numbers do you want?\n> ";
cin >> count;
// Create a dynamic array with size 'count'
int *myArray = new int[count];
for(int i = 0; i < count; i++)
{
// Ask for numbers here
}
// Make sure to delete it afterwars
delete[] myArray;
If you pass an int by value, you will not be able to change the callers value. But if you pass a pointer to the int, you can change it. This is how C changed parameters. C++ can pass values by reference so this is less useful.
f(int i)
{
i= 10;
std::cout << "f value: " << i << std::endl;
}
f2(int *pi)
{
*pi = 10;
std::cout << "f2 value: " << pi << std::endl;
}
main()
{
i = 5
f(i)
std::cout << "main f value: " << i << std::endl;
f2(&i)
std::cout << "main f2 value: " << i << std::endl;
}
in main the first print should still be 5. The second one should be 10.
What is the purpose in going through the added layer for another variable or pointer?
There isn't one. It's a deliberately contrived example to show you how the mechanism works.
In reality, objects are often stored, or accessed from distant parts of your codebase, or allocated dynamically, or otherwise cannot be scope-bound. In any of these scenarios you may find yourself in need of indirectly referring to objects, and this is achieved using pointers and/or references (depending on your need).
For example some objects have no name. It can be an allocated memory or an address returned from a function or it can be an iterator.
In your simple example of course there is no need to declare the pointer. However in many cases as for example when you deal with C string functions you need to use pointers. A simple example
char s[] = "It is pointer?";
if ( char *p = std::strchr( s, '?' ) ) *p = '!';
We use pointers mainly when we need to allocate memory dynamically. For example,To implement some data structures like Linked lists,Trees etc.
From C# point of view pointer is quite same as Object reference in C# - it is just an address in memory there actual data is stored, and by dereferencing it you can manipulate with this data.
First of non-pointer data like int in your example is allocated on the stack. This means that then it goes out of the scope it's used memory will be set free. On the other hand data allocated with operator new will be placed in heap (just like then you create any Object in C#) resulting that this data will not be set free that you loose it's pointer. So using data in heap memory makes you do one of the following:
use garbage collector to remove data later (as done in C#)
manually free memory then you don't need it anymore (in C++ way
with operator delete).
Why is it needed?
There are basically three use-cases:
stack memory is fast but limited, so if you need to store big
amount of data you have to use heap
copying big data around is
expensive. Then you pass simple value between functions on the stack
it does copying. Then you pass pointer the only thing copied is just
it's address (just like in C#).
some objects in C++ might be
non-copyable, like threads for example, due to their nature.
Take the example where you have a pointer to a class.
struct A
{
int thing;
double other;
A() {
thing = 4;
other = 7.2;
}
};
Let's say we have a method which takes an 'A':
void otherMethod()
{
int num = 12;
A mine;
doMethod(num, mine);
std::cout << "doobie " << mine.thing;
}
void doMethod(int num, A foo)
{
for(int i = 0; i < num; ++i)
std::cout << "blargh " << foo.other;
foo.thing--;
}
When the doMethod is called, the A object is passed by value. This means a NEW A object is created (as a copy). The foo.thing-- line won't modify the mine object at all as they're two separate objects.
What you need to do is to pass in a pointer to the original object. When you pass in a pointer, then the foo.thing-- will modify the original object instead of creating a copy of the old object into a new one.
Pointers (or references) are vital for the use of dynamic polymorphism in C++. They are how you use a class hierarchy.
Shape * myShape = new Circle();
myShape->Draw(); // this draws a circle
// in fact there is likely no implementation for Shape::Draw
Attempts to use a derived class through a value (instead of pointer or reference) to a base class will often result in slicing and losing the derived data portion of the object.
It makes a lot more sense when you're passing the pointer to a function, see this example:
void setNumber(int *number, int value) {
*number = value;
}
int aNumber = 5;
setNumber(&aNumber, 10);
// aNumber is now 10
What we're doing here is setting the value of *number, this would not be possible without the use of pointers.
If you defined it like this instead:
void setNumber(int number, int value) {
number = value;
}
int aNumber = 5;
setNumber(aNumber, 10);
// aNumber is still 5 since you're only copying its value
It also gives better performance and you're not wasting as much memory when you're passing a reference to a larger object (such as a class) to a function, instead of passing the whole object.
Well to use pointers in programming is a pretty concept. And for dynamically allocating the memory it is essentiall to use pointers to store the adress of the first location of the memory which we have reserved and same is the case for releasing the memory, we need pointers. It's true as some one said in above answer that u cannot understand the use of poinetrs until u need it. One example is that u can make a variable size array using pointers and dynamic memoru allocation. And one thing important is that using pointers we can change the actual value of the location becaues we are accessing the location indirectly. More ever, when we need to pass our value by refernce there are times when references do not work so we need pointers.
And the code u have written is using dereference operator. As i have said that we access the loaction of memory indirectly by using pointers so it changes the actuall value of the location like reference objects that is why it is printing 10.