|
My teacher keeps on saying this is wrong although it works fine for me. He says that after I delete queue, the local queue pointer will be assigned the address of the new Queue-object and it won't be returned to Main and the original queue pointer because it's a copy.
But when I test it it does, both pointers have the same address all the time according to VS debug and I also see the capacity changes. My teacher told me to return the "copy" pointer from the function (queue = newQueue(queue)) which I tried and it did exactly the same thing.
Queue *queue = new Queue; //default capacity 10 newQueue(queue);
void newQueue(Queue *queue){ ... cin >> capacity; delete queue; queue = new Queue(capacity); }
|
Well, he's right. You are assigning to a local pointer. Maybe VS does some magic so it works (like inlining since it's such a small function? Then again there should be no inlining in debug...).
You could use a reference to a Queue * as function argument. That way you would assign to the original pointer.
|
It works in your case for one simple reason - the second time you create the object, it gets created at the same memory address as the first time, because that first object got deleted and the memory got released. Pure coincidence, in other words. In general, this will not work. Test by commenting out the delete.
|
Just because it works by accident (which could be for any number of reasons) doesn't mean you should do it.
My guess would be that your heap is allocating the new Queue where the old queue was deleted from.
outer_queue = new Queue //allocates memory at location X, constructs a queue object on top newQueue(outer_queue)
void (newQueue* inner_queue) { delete inner_queue; //delete destructs the object at location X and allows the memory at // X to be reused. inner_queue and outer_queue both still point at X inner_queue = new Queue(capacitiy) //allocates memory at location X (because it was // the most recently free'd block of memory) and // constructs the new queue }
Both inner_queue and outer_queue point at X, which is a valid object.
You got away with murder because your allocator just happened to allocate the new object at the same spot. If your allocator behaved differently and allocated the second Queue object at Y, inner_queue would point at Y and outer_queue would point at X, where X is no longer a valid Queue object.
|
TossFloss
Canada606 Posts
Your teacher should ditch C++. >_< This makes me rage so much. Bloated OOP languages do not make good educational language for first time programmers.
Anyways, your teacher is right. Your code just happens to work in this particular instance.
Here's what you need to understand. Queue * queue is a pointer to an object of type Queue.
Pointers and memory are not magical like crappy C++ makes them look. They are a number which points to an address in memory. The variable queue merely stores a number (e.g. 283840).
Let's break this down:
The type of variable---> Queue *<-- tells you this is a pointer queue <--- the name of your variable
Maybe you're wondering why we need to declare the type of variable queue stores i.e. what's up with the Queue in Queue *. Well we don't need to (more below). It's a nice feature called type checking which tries to make sure that when you compile your code you didn't accidentally think a queue object was a frog object and get them mixed up and then run code blocks like queue->jump(); queue->croak() and have your code crash terribly during runtime. Instead it spit out a nice compiler error.
However, you can shoot yourself in the foot like this: void * queue void * lets you make a pointer which can point to anything even a Frog.
Now let's go to the next important magical keyword in the C++ language. The magic new keyword.
new Queue;
This says to the operating system: Give me a chunk of memory large enough to fit a queue. Then the operating tries to allocate that much memory and gives you a memory address pointing to your memory.
Imagine that you are Miley Cyrus and your family has hundreds of fancy cars/vans/trucks - way too many for Miley's brain to keep track of. Some vehicles aren't available because they are being used, re-styled or someone like me stole them. So you being Miley Cyrus have a party with 6 other people that all need to fit into a car. So you need a vehicle for 7 people. You go to your butler and say "I need a vehicle that will fit exactly 7 people". He gives you the keys and parking spot number of such a vehicle. Your butler's like an OS and that parking spot number/keys is like a memory address.
Of course the OS might have no memory to give you (or might be really greedy and want to keep it all for itself) in which case it will tell you to gtfo. But this will probably never happen in any of your courses.
Please remember that the new keyword requests a fixed size of memory WHICH is known at compile time. You know how much memory is needed for a Queue object (your compiler does). Say your Queue object is a monster and takes up 256 bytes. Then new Queue is like saying: Operating System please set aside 256 bytes for my own personal use and give me the memory address.
So why does your code work? Because for some fluke of luck the queue you create in the newQueue function has the same memory address as the queue you deleted. If you wanna make it break: remove the delete queue line.
|
You could use a reference to a pointer instead of a plain pointer in the parameters: void newQueue(Queue*& queue){...}. Or you can return a Queue* from your function: Queue* newQueue(Queue* oldqueue){...}; so that you can do q = newQueue(q) stuff. Then it will modify the pointer. Obviously the way it is now, it does not.
Also, your code is rather fishy, use a constructor with std::istream& as parameter, or an operator >> to read from std::in; then all you need to do if you want to use it:
Queue q(std::in); or Queue* q = new Queue(std::in); or Queue q; std::cin >> q; or Queue* q = new Queue(); std::cin >> (*q); depending on how you want to use it.
I recommend you implement it with std::list (or std::vector for stack), that way you can easily insert/delete/resize without screwing around with pointers.
|
Hyrule18934 Posts
Put another variable declaration between the delete and instantiation, otherwise you'll get the first available address (the one you just cleared). Not hard to follow.
|
I am assuming that the OP is forced to use a queue by their teacher. Having said that, I agree that C++ should not be taught as a first language.
The reason it works is purely coincidental. I am inclined to agree with georgir and Mumblee that the reason it works in this particular case is that coincidentally the new Queue is created at the same memory address as the old one. There are three solutions:
1) Your teacher is right. Returning the local pointer and assigning that value would work.
Queue* q = new Queue(); q = newQueue(q);
Queue* newQueue(Queue* q) { /* ...snip... */ cin >> c; delete q; q = 0; q = new Queue(c); return q; }
2) The C way. Pass a pointer to a pointer.
Queue* q = new Queue(); newQueue(&q);
void newQueue(Queue** q) { /* ...snip... */ Queue * ptr = (*q); // More readable cin >> c; delete ptr; ptr = new Queue(c); }
3) The C++ way, that has already been mentioned before: Pass a reference.
Queue* q = new Queue(); newQueue(q);
void newQueue(Queue&* q) { /* ...snip... */ cin >> c; delete q; q = new Queue(c); }
Now since you obviously don't quite grasp the concept of pointers and passing by value yet, I would advise to go with the method your teacher suggest. In the end though it's a matter of style. Whichever way you decide to go with, make sure you understand what's happening and be consistent.
Having said all that, it horrifies me that your teacher is teaching you to delete an input parameter in a function that, by name, is claiming to create something. Please call the thing something along the lines of replaceQueue(...)
|
Alright thanks guys, I understand the problem now. I used a return like teacher told me to and it's all good.
TossFloss: ROFL dude, I wish I had a teacher like you instead, you're funny and way better at explaining :D
I'm not a newbie to programming, I'm soon done with my 3 years CS program. However I'm newbie to C++ OOP and just read a introduction C++ course before this one. I know Java/C# OOP well but could never imagine something as easy as making a new object from an old would cause so many problems in C++. I'm used to memory management being all automatic... anyway thanks once again and I hope one day I won't be scared of pointers and instead find them useful!
|
On October 13 2010 23:49 Freezard wrote: Alright thanks guys, I understand the problem now. I used a return like teacher told me to and it's all good.
TossFloss: ROFL dude, I wish I had a teacher like you instead, you're funny and way better at explaining :D
I'm not a newbie to programming, I'm soon done with my 3 years CS program. However I'm newbie to C++ OOP and just read a introduction C++ course before this one. I know Java/C# OOP well but could never imagine something as easy as making a new object from an old would cause so many problems in C++. I'm used to memory management being all automatic... anyway thanks once again and I hope one day I won't be scared of pointers and instead find them useful! The danger of switching from managed languages like Java and C# to C or C++ -- a danger your teacher should be aware of and should hammer on right from the start! -- is that these languages implicitly pass parameters by reference, and not by value. In a managed language your code would be correct because of this.
IN C AND C++ ALL PARAMETERS ARE COPIES OF WHAT YOU PASS!
If you pass an object, the function gets a copy of it. If you pass a pointer to an object, the function gets a copy of the pointer. References, even in C++, are a fancy way of hiding this. While that's nice and could most certainly make code more readable (especially in situations like these where you start having to use pointers to pointers) it can also be destructive if you don't understand what you're doing.
|
On October 13 2010 22:38 TossFloss wrote: Your teacher should ditch C++. >_< This makes me rage so much. Bloated OOP languages do not make good educational language for first time programmers.. What language would you prefer?
I learned C as my first language, followed by C++ and I feel like it's given me a better understanding of the hardware/software interaction than say Python or Java. Of course I am a computer engineer so I care about details (and speed!).
|
On October 13 2010 23:41 Shenghi wrote:3) The C++ way, that has already been mentioned before: Pass a reference. Queue* q = new Queue(); newQueue(q);
void newQueue(Queue&* q) { /* ...snip... */ cin >> c; delete q; q = new Queue(c); }
mind = blown I did not know you could reference a pointer.
|
Also WHY are you doing it this way? You are essentially creating an object and then immediately destroying it to create another object?. You could just skip that step and just do
cin << cap; Queue* q = new Queue(cap);
Unless of course this is just an intellectual exercise.
|
Also, your code is rather fishy, use a constructor with std::istream& as parameter, or an operator >> to read from std::in; then all you need to do if you want to use it:
Ewww. That's awful coding practice. What if you wanted to create the object from a capacity value that wasn't pulled from a std:istream? Maybe something you compute based on the time of day? Or something else?
Object constructors should take the bare minimum necessary to build a working object of that type. No more. It places a dependency between that object and std::istream that is entirely unnecessary.
|
On October 14 2010 01:10 Uranium wrote:Show nested quote +On October 13 2010 23:41 Shenghi wrote:3) The C++ way, that has already been mentioned before: Pass a reference. Queue* q = new Queue(); newQueue(q);
void newQueue(Queue&* q) { /* ...snip... */ cin >> c; delete q; q = new Queue(c); }
mind = blown I did not know you could reference a pointer. You can, but it's not a very nice thing to do usually. It certainly wouldn't be my option of choice. But in the end a pointer is just a 4-byte (x86) value that can be passed like anything else, which includes passing by reference.
And to answer the which language first question: Java or C# like the OP apparently did get first would be fine. Not all of us grew up in an age where these were non-existent, or where it was vital for every programmer to understand the underlying architecture. In this day and age, however, it can give quite the edge as most CS graduates never really learn the lower level languages.
I personally did learn C as a first language and then C++, but I taught myself. A couple years late, I'm now attending uni and see how many problems other students have with Java already. If C or C++ was the first language they learned then even more people would fail.
|
TossFloss
Canada606 Posts
On October 14 2010 01:07 Uranium wrote:Show nested quote +On October 13 2010 22:38 TossFloss wrote: Your teacher should ditch C++. >_< This makes me rage so much. Bloated OOP languages do not make good educational language for first time programmers.. What language would you prefer? I learned C as my first language, followed by C++ and I feel like it's given me a better understanding of the hardware/software interaction than say Python or Java. Of course I am a computer engineer so I care about details (and speed!).
Straight up C with K&R as the course text.
And to answer the which language first question: Java or C# like the OP apparently did get first would be fine. Not all of us grew up in an age where these were non-existent, or where it was vital for every programmer to understand the underlying architecture. In this day and age, however, it can give quite the edge as most CS graduates never really learn the lower level languages.
If I interview a CS graduate who doesn't understand memory allocation after four years of supposed education, they do not get the job. Too many programmers possess zero knowledge of how their program allocate and reference memory, and consequently their programs are slow, bloated and buggy.
|
On October 14 2010 01:47 Shenghi wrote:Show nested quote +On October 14 2010 01:10 Uranium wrote:On October 13 2010 23:41 Shenghi wrote:3) The C++ way, that has already been mentioned before: Pass a reference. Queue* q = new Queue(); newQueue(q);
void newQueue(Queue&* q) { /* ...snip... */ cin >> c; delete q; q = new Queue(c); }
mind = blown I did not know you could reference a pointer. You can, but it's not a very nice thing to do usually. It certainly wouldn't be my option of choice. But in the end a pointer is just a 4-byte (x86) value that can be passed like anything else, which includes passing by reference. And to answer the which language first question: Java or C# like the OP apparently did get first would be fine. Not all of us grew up in an age where these were non-existent, or where it was vital for every programmer to understand the underlying architecture. In this day and age, however, it can give quite the edge as most CS graduates never really learn the lower level languages. I personally did learn C as a first language and then C++, but I taught myself. A couple years late, I'm now attending uni and see how many problems other students have with Java already. If C or C++ was the first language they learned then even more people would fail.
Meh I think building up from the basics of C is much better than trying to come down to the basics after learning a higher level language such as Java. People who start at Java and try to go down any lower really have no idea of what is going on underneath their code. When you peel off the layers of abstraction that Java adds, there is nothing left for those guys. Someone who knows C can easily bump up to a higher level language like C++ or Java.
|
Best option would be to implement The Big Three properly and then just create your Queue objects on the stack. There is probably no reason for them to be on the heap for you. If you want a factory convenience function just return it by value. Your compiler will perform return value optimization (RVO).
Queue createQueue() { ... std::cin >> capacity; return Queue(capacity); }
Queue queue; // default capacity 10 ... queue = createQueue();
More simples.
|
TossFloss
Canada606 Posts
On October 14 2010 02:04 waxypants wrote:Show nested quote +On October 14 2010 01:47 Shenghi wrote:On October 14 2010 01:10 Uranium wrote:On October 13 2010 23:41 Shenghi wrote:3) The C++ way, that has already been mentioned before: Pass a reference. Queue* q = new Queue(); newQueue(q);
void newQueue(Queue&* q) { /* ...snip... */ cin >> c; delete q; q = new Queue(c); }
mind = blown I did not know you could reference a pointer. You can, but it's not a very nice thing to do usually. It certainly wouldn't be my option of choice. But in the end a pointer is just a 4-byte (x86) value that can be passed like anything else, which includes passing by reference. And to answer the which language first question: Java or C# like the OP apparently did get first would be fine. Not all of us grew up in an age where these were non-existent, or where it was vital for every programmer to understand the underlying architecture. In this day and age, however, it can give quite the edge as most CS graduates never really learn the lower level languages. I personally did learn C as a first language and then C++, but I taught myself. A couple years late, I'm now attending uni and see how many problems other students have with Java already. If C or C++ was the first language they learned then even more people would fail. Meh I think building up from the basics of C is much better than trying to come down to the basics after learning a higher level language such as Java. People who start at Java and try to go down any lower really have no idea of what is going on underneath their code. When you peel off the layers of abstraction that Java adds, there is nothing left for those guys. Someone who knows C can easily bump up to a higher level language like C++ or Java.
My other issue with C++ is that it's bloated with keywords and higher-level concepts.
For example, a new learner get beffedudled keeping of tracking of: what's this namespace thing and why do I care; what's up with these magic << and >> operators; how do I make sense of objects; so I can functions with objects and functions without objects; constructors and destructors; class variables.
At the same time they have to figure out the building blocks of programs (for, while, if, else, char, int, array, ...) and language syntax. And really it's too much information to absorb and digest.
As a reference: here's a list of C++ keywords contrast to the list of C keywords.
|
Heh, the very first programming language I had to learn was Turbo Pascal Man I hated this shit...
|
|
|
|