|
Too lazy to quote people:
@TossFloss
Eventually you'll run out of graduates to hire. In a couple of years nobody will learn lower level languages anymore, and unless they take a minor that covers architecture they will not know anything. I agree that they should know. When looking at the university that I am attending, after two years those who did not start their studies with prior knowledge have only a vague notion of scope and none whatsoever of ownership. And I didn't even start about memory yet. It's sad but unfortunately true.
I have to agree that C would be better as a first language than C++ for exactly the reasons you're giving.
@dvide
Please, pretty please, do not return objects by value. What if I decided to make a queue of size MAX_INT?
@waxypants
You have a point, but it would require a complete overhaul of how people are currently taught.
@nobody in particular
The (sad) truth is that many companies don't care whether or not their grads understand things like memory allocation. With the current systems a bloated app written in a managed language will often run "fast enough," as long as they're not too buggy. A CS grad who knows Java and has a vague notion of basics is also a lot cheaper than someone who knows their stuff. Not to mention faster (because he isn't nice and tidy.)
To be honest it doesn't matter which languages are taught. Most fresh CS grads are not competent programmers regardless of which language they have been taught. They would of course lack experience, but more importantly most universities don't teach their CS students basic concepts, or how to reason about programs. In the end the language of choice is just a tool.
[BTW] We're going way off topic :p
[edit] Based on what most companies are looking for, any managed language as first language would be better than C or C++. When it comes to competence I wholeheartedly agree that C should be the first language.
|
On October 14 2010 02:19 TossFloss wrote:Show nested quote +On October 14 2010 02:04 waxypants wrote: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.
I think we can all agree that C++ is terrible as a first language. It does not seem that C++ is the OP's first language anyway.
With regards to whether Java or C is better, it really is a question of teaching style. Is it better to learn the high level concepts first, without the clutter of low level implementation? Or is it better to understand the underlying mechanics and build up to higher level understanding?
My personal opinion is that the first approach (i.e. Java or python first) is better. My reasoning is that we want to reduce the number of things that one has to learn to start accomplishing basic tasks, and it's easier to build from a less complex core of knowledge. C++ is obviously terrible in this regard. C is nice in that it exposes the underlying hardware in a more clean fashion, but it may still be more frustrating for someone to have to deal with it if they're just getting started. I also do not think there is an issue with the transition from Java to C, as long as it is approached correctly. You just have to gradually peel the onion of computer science, one layer at a time.
In the end, both methods are perfectly viable. Everyone has to learn all the basics from low to high at some point, so whichever direction you go, you should end up with the same result, if done correctly.
|
On October 14 2010 01:13 Uranium wrote: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. The program starts with a Queue with default cap and then you can choose to create a new one on a menu. It wasn't even necessary in the assignment to make a new one, you were supposed to let them choose capacity one time and then stick with it, but yea... felt cheap to me.
Also I'm happy I started with Java. Well that's not entirely true because the first language we learn is Haskell which is a functional language. But I had enough trouble with Java in the beginning that I feel that if I had started with C++ instead of Java I woulda ragequit school as soon as we had to learn pointers.
I did read two courses in digital electrics and computer engineering where we were programming in assembly (along with C later on) which is as close to machine language you can come. It was really fun because we got to program a drill among other things but I also learned a lot about memory management. I really didn't know everything was passed by value in C++, thanks for pointing that out because it makes a lot more sense now.
I'll go on finishing my second assignment which has been a lot easier thanks to my new knowledge <3 TL!
|
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? You're not limited to one constructor. Feel free to write additional ones that make sense in light of the given problem. std::istream in this case. Time of the day / CPU time in the case of a random generator. Or in the case of one of my classes, Image<double>("filename.png", ImageRGB), Image<double>(640, 480, ImageRGB), Image<double>(sourceImage), et cetera.
Object constructors should take the bare minimum necessary to build a working object of that type. No more. Where do you get this silly idea? What you have described is essentially constructing an object via the default constructor and a load of setter functions, which I'm pretty sure is an antipattern, causes redundant assigments, and is discouraged by a lot of common practices, including Effective C++. You should write constructors and public access functions and operators that are intuitive, easy to use, make sense within the context of the problem, and are well documented. In case you were thinking about default constructors, I completely agree.
It places a dependency between that object and std::istream that is entirely unnecessary. Lot of the times istream is already included, so that's usually not a problem. In the cases it does cause problems, you are doing something very very wrong. And just because a completely legitimate, easy and clever way to initialize an object involves a dependency, is no grounds to outright disregard it. (Yes, circular dependencies are evil, but are easily resolved with predeclarations, template trickery or some other way)
|
On October 14 2010 02:48 Slithe wrote:Show nested quote +On October 14 2010 02:19 TossFloss wrote:On October 14 2010 02:04 waxypants wrote: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. I think we can all agree that C++ is terrible as a first language. It does not seem that C++ is the OP's first language anyway. With regards to whether Java or C is better, it really is a question of teaching style. Is it better to learn the high level concepts first, without the clutter of low level implementation? Or is it better to understand the underlying mechanics and build up to higher level understanding? My personal opinion is that the first approach (i.e. Java or python first) is better. My reasoning is that we want to reduce the number of things that one has to learn to start accomplishing basic tasks, and it's easier to build from a less complex core of knowledge. C++ is obviously terrible in this regard. C is nice in that it exposes the underlying hardware in a more clean fashion, but it may still be more frustrating for someone to have to deal with it if they're just getting started. I also do not think there is an issue with the transition from Java to C, as long as it is approached correctly. You just have to gradually peel the onion of computer science, one layer at a time. In the end, both methods are perfectly viable. Everyone has to learn all the basics from low to high at some point, so whichever direction you go, you should end up with the same result, if done correctly.
Well, I'm not a competent programmer myself, but I did try to learn a couple languages myself and I hate to say after a while that going structural (C) -> object oriented (Java) is easier than the other way around. Object oriented programming (especially when you can use classes) seems to me faster/easier than structural and if you learn OO first, you might meet a lot of barriers when you try ST and have to do a lot of things "manually".
|
On October 14 2010 02:48 Shenghi wrote: @dvide
Please, pretty please, do not return objects by value. What if I decided to make a queue of size MAX_INT? Then you'll make a big queue, but no extra copies of it will be made from the factory function due to RVO as I mentioned. If you want to avoid copies in other contexts then pass it around as a reference, but do try to keep it on the stack unless you have a good reason. For sure sometimes it is best to put an expensive-to-copy object on the heap if you'd have no other choice than to unnecessarily copy it often, but this is messy and should not be default behaviour (and thankfully it's resolved in the upcoming changes to the C++ standard). Plus in a lot of these cases you can get away with using a specialised swap function (which you will probably have anyway if you implement the copy-and-swap idiom) to steal resources. But in most use cases it will probably be faster to access your object directly than through a pointer in some premature effort to merely to avoid a few minor copies.
It's certainly better than putting all deep-copy objects onto the heap all of the time and using pointer semantics everywhere in a paranoid attempt to avoid copies without even measuring it. You will get none of the benefits of using automatic variables for resource management (RAII). This will lead to more problems in the long term, especially when you start getting into requiring exception safety. Values are your friends.
On October 14 2010 03:36 Frigo wrote:Show nested quote +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? You're not limited to one constructor. Feel free to write additional ones that make sense in light of the given problem. std::istream in this case. Time of the day / CPU time in the case of a random generator. Or in the case of one of my classes, Image<double>("filename.png", ImageRGB), Image<double>(640, 480, ImageRGB), Image<double>(sourceImage), et cetera. Show nested quote +Object constructors should take the bare minimum necessary to build a working object of that type. No more. Where do you get this silly idea? What you have described is essentially constructing an object via the default constructor and a load of setter functions, which I'm pretty sure is an antipattern, causes redundant overwrites, and is discouraged by a lot of common practices, including Effective C++. You should write constructors and public access functions and operators that are intuitive, easy to use, make sense within the context of the problem, and are well documented. In case you were thinking about default constructors, I completely agree. Show nested quote +It places a dependency between that object and std::istream that is entirely unnecessary. Lot of the times istream is already included, so that's usually not a problem. In the cases it does cause problems, you are doing something very very wrong. And just because a completely legitimate, easy and clever way to initialize an object involves a dependency, is no grounds to outright disregard it. (Yes, circular dependencies are evil, but are easily resolved with predeclarations, template trickery or some other way) If all that your object requires is an A to construct itself, then just take an A in the constructor. Don't take a B and then ask it to get an A for you. Then creates an unnecessary coupling with B. See the Law of Demeter. If some complex but frequent procedure is needed to build an object then just use some creational pattern. This separates concerns nicely.
|
@dvide
Whoops, I completely read over the RVO part of your post. Sorry. I still wouldn't do it that way, but that's simply a matter of taste.
I do agree that when something doesn't absolutely need to be on the heap, it shouldn't be.
|
Queue *queue = new Queue; //default capacity 10 newQueue(queue);
void newQueue(Queue *queue){ ... cin >> capacity; delete queue; queue = new Queue(capacity); }
This code makes me wanna puke. Blheh. Please learn to program in a way dvide suggested :
On October 14 2010 02:15 dvide wrote: Queue createQueue() { ... std::cin >> capacity; return Queue(capacity); }
Queue queue; // default capacity 10 ... queue = createQueue();
As a good rule try to never use new. If you have to use it in a wrapper in constructor and make sure to delete the object in destructor. Or use boost::shared_ptr<your_type>, then you don't have to worry about destructions. This will actually also start to get useful later when you will want to make your objects copy-able, but with some parts referencing to the same object(now too compicated for beginners).
|
On October 14 2010 05:19 LastWish wrote: Queue *queue = new Queue; //default capacity 10 newQueue(queue);
void newQueue(Queue *queue){ ... cin >> capacity; delete queue; queue = new Queue(capacity); }
This code makes me wanna puke. Blheh. Please learn to program in a way dvide suggested : Show nested quote +On October 14 2010 02:15 dvide wrote: Queue createQueue() { ... std::cin >> capacity; return Queue(capacity); }
Queue queue; // default capacity 10 ... queue = createQueue();
As a good rule try to never use new. If you have to use it in a wrapper in constructor and make sure to delete the object in destructor. Or use boost::shared_ptr<your_type>, then you don't have to worry about destructions. This will actually also start to get useful later when you will want to make your objects copy-able, but with some parts referencing to the same object(now too compicated for beginners). Doesn't work I get heap error after I create new queue and try to enqueue an item T_T
How can you assign an object to a variable without using new? That makes no sense since the new word allocated memory.
enqueue(&queue); void enqueue(Queue *queue){ queue->enqueue(element); }
|
you want to pass in Queue** or Queue*& if u want to change Queue*
|
On October 14 2010 05:50 imDerek wrote: you want to pass in Queue** or Queue*& if u want to change Queue* Wut? Excuse me? Do you have to use double pointers when I don't even understand single pointers? I'm sure that's a better way but also more complicated...
And yes btw it has to be a dynamic object which I assume Queue queue can never be (since you can't use new/delete on it).
|
On October 14 2010 04:02 dvide wrote:If all that your object requires is an A to construct itself, then just take an A in the constructor. Don't take a B and then ask it to get an A for you. Then creates an unnecessary coupling with B. See the Law of Demeter. If some complex but frequent procedure is needed to build an object then just use some creational pattern. This separates concerns nicely. Cool, didn't know about this particular (anti)pattern yet. Though I fail to recognize how it applies in this particular case. std::istream does not contain the integer we read in, there is absolutely no coupling between the three. Especially since the integer is not an object, only an instance of a primitive type, a constant return value we will simply discard (more properly, store in another integer). We can not implement the behavior in std::istream either, it simply can't do anything with our Queue class. No need for any wrappers either.
|
On October 14 2010 05:48 Freezard wrote: Doesn't work I get heap error after I create new queue and try to enqueue an item T_T
How can you assign an object to a variable without using new? That makes no sense since the new word allocated memory.
Your class should define a copy constructor and assignment operator that handles the semantics of this operation properly (and a destructor, but I'll assume you already have that). This is probably the most important thing to understand in C++ (trust me), so I'd make it a priority. It's a little bit complicated, but once you've got it down you'll understand why and it will save you a lot of headaches down the road. Be warned, for it may even make you enjoy programming in C++ 
The compiler generates a hidden, default implementation of these functions for you (which is why it compiles), but in this case the default implementations are incorrect and that is what is ultimately causing your heap errors. The default generated functions simply do a memberwise copy of your object's variables, but what you want instead is deep-copy semantics.
If your queue object owns some memory (which I assume it does), it will have a pointer member variable. The default generated copy constructor and assignment operator functions simply copy the pointer value to another queue object, which means that now two queue objects share ownership of the same memory location. When one of your queue objects is destroyed its destructor is called, which will then proceed to delete its memory. This will leave your other queue object with a dangling pointer to already freed memory, and when accessed you will therefore get undefined behaviour (such as your heap error).
What you want to do instead is create a copy constructor that allocates more memory for itself and copies the old data into it. So now each queue object is unique and owns its own memory, but the value of the two queues are still semantically identical (i.e. a copy). The assignment operator should do essentially the same thing. It needs to free it's own memory and allocate itself more memory and then copy the rhs (right hand side) data into it.
The assignment operator can actually be written in-terms of the copy constructor and destructor (and a swap function), which is very nice for code reuse. This is the cleanest way to write the functions, and is referred to as the copy-and-swap idiom. Even though the above is a lot of explanation, the actual idiom is quite small and takes minimal effort to implement.
class Queue { private: std::size_t m_capacity; // basically an unsigned int int* m_data;
public: Queue(std::size_t capacity) // an initialisation list (google it if you don't know it) : m_capacity(capacity), m_data( new int[capacity]() ) { } // Copy constructor Queue(const Queue& rhs) // must take rhs param by const ref // Allocates its own memory area large enough to hold rhs's data ... : m_capacity(rhs.m_capacity), m_data( new int[rhs.m_capacity] ) { // ... and then copies rhs's data into it std::copy( rhs.m_data, rhs.m_data + m_capacity, m_data );
// include <algorithm> for std::copy } // Assignment operator // Take rhs param by value, it invokes the copy constructor above Queue& operator=(Queue rhs) { swap(*this, rhs); // swap our contents with rhs (a cheap operation) return *this;
// rhs goes out of scope, invoking its destructor // (it will free the memory we used to own) }
// Swap our members friend void swap(Queue& a, Queue& b) { using std::swap; // include <utility> for std::swap swap(a.m_capacity, b.m_capacity); swap(a.m_data, b.m_data); }
// Free the memory we own ~Queue() { delete [] m_data; }
... enqueue functions, etc. ... I'm unconcerned with that, as this is just about managing resources ... tried to keep this example as simple as possible }
Queue q1; Queue q2(q1); // Invokes copy constructor Queue q3 = q1; // Invokes copy constructor (exactly the same as above) q1 = q2; // Invokes assignment operator (not an initialisation)
Hope that all makes sense.
|
// Assignment operator Queue& operator=(Queue rhs) // take param by value, it invokes the copy constructor above { swap(*this, rhs); // swap our contents with the rhs (a cheap operation) return *this; // rhs goes out of scope, invoking its destructor (it will free the memory we used to own) }
Actually this seems to be wrong. Queue& operator=(Queue& rhs) If you omit the & you may get into trouble because : - rhs will be a temporal object - rhs might not be deallocated properly if this == &rhs
Quick google find : http://www.fredosaurus.com/notes-cpp/oop-overloading/overloadassign.html
|
On October 14 2010 06:39 Frigo wrote:Show nested quote +On October 14 2010 04:02 dvide wrote:If all that your object requires is an A to construct itself, then just take an A in the constructor. Don't take a B and then ask it to get an A for you. Then creates an unnecessary coupling with B. See the Law of Demeter. If some complex but frequent procedure is needed to build an object then just use some creational pattern. This separates concerns nicely. Cool, didn't know about this particular (anti)pattern yet. Though I fail to recognize how it applies in this particular case. std::istream does not contain the integer we read in, there is absolutely no coupling between the three. Especially since the integer is not an object, only an instance of a primitive type, a constant return value we will simply discard (more properly, store in another integer). We can not implement the behavior in std::istream either, it simply can't do anything with our Queue class. No need for any wrappers either. The principle of least knowledge as I understand it is like this: if you want some money from a customer don't ask for their wallet so that you can take the money out by yourself. Just ask for money directly. There is no reason for you to be coupled to the wallet in any way. It makes it harder to unit test the class in isolation for example, since now you have a dependency on wallet that is not strictly needed. Indeed, you only added the dependency for a convenience case, so a simple factory function would serve us better in that case.
|
private: int* m_data; std::size_t m_capacity; // basically an unsigned int
public: Queue(std::size_t capacity) // an initialisation list (google it if you don't know it) : m_capacity(capacity), m_data( new int[capacity]() ) { }
Initialisation list isn't initialized according to the order in which they are mentioned in the constructor, rather the order in the class definition.
private: std::size_t m_capacity; // basically an unsigned int int* m_data;
In this case you don't even have to use initialization lists, since it makes no performance gain. Although your stuff works since you used new int[capacity] and not m_capacity.
|
On October 14 2010 07:56 LastWish wrote: // Assignment operator Queue& operator=(Queue rhs) // take param by value, it invokes the copy constructor above { swap(*this, rhs); // swap our contents with the rhs (a cheap operation) return *this; // rhs goes out of scope, invoking its destructor (it will free the memory we used to own) }
Actually this seems to be wrong. Queue& operator=(Queue & rhs) If you omit the & you may get into trouble because : - rhs will be a temporal object - rhs might not be deallocated properly if this == &rhs Quick google find : http://www.fredosaurus.com/notes-cpp/oop-overloading/overloadassign.html Temporal object. Sweet, is that out of star trek? 
The copy-and-swap idiom must always make a temporary copy. So you might as well copy it in the parameter list because then the compiler can elide it sometimes if it comes from an rvalue. See this article: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
Self assignment does not lead to a bug in this case. It's not as efficient as specifically checking for it, because we still must make a copy. But we can't check for it if we take the parameter by value, this is true. But we shouldn't optimise for this minor corner case when we get much more gains from copy elision here (as Dave Abrahams mentions in a comment of the article I linked to).
That assignment operator link you sent also does not provide a strong exception guarantee, where as the copy and swap idiom does. If new char throws a bad_alloc exception, for instance the state of the object is left all messed up.
On October 14 2010 08:14 LastWish wrote: Initialisation list isn't initialized according to the order in which they are mentioned in the constructor, rather the order in the class definition.
Thanks, I've corrected that.
EDIT: Also fixed the call to std::copy. Had the parameters wrong.
|
|
|
|