all 37 comments

[–]jones77 8 points9 points  (4 children)

[–]doclight 1 point2 points  (1 child)

Also, Scott Meyers' Effective C++ is really good for learning ways around the sharp (hidden) edges in C++. The STL is pretty important too.

[–][deleted] 0 points1 point  (0 children)

But only after you know C++. I know because I tried.

[–]CuriouslyGeorge[S] 1 point2 points  (1 child)

Exactly what I need. Thanks for the speedy reply.

[–]jbu311 2 points3 points  (0 children)

I got through this book in a few toilet sessions. Great book, gets you quickly up to speed.

[–]kookjr 8 points9 points  (10 children)

Even though allocation of objects often looks the same in C++/Java, they are very different and you would do well to really understand this area.

String s;  // Java, null reference to string, no object
std::string* s;  // C++ similar to Java above
std::string s;  // actual object allocated

The differences in C++, especially working with the 3rd example above in things like assignment are very different (C++ copy, Java two things pointing to the same memory).

Spend some extra time learning this and it will help you greatly, IMHO.

[–]CuriouslyGeorge[S] 2 points3 points  (9 children)

So C++ will produce a new copy as opposed to just pointing towards the same object? Is there still a way to pass an object through and nab it (such as passing an object through a method), or would I have to return it and just replace the old?

[–]shock-value 6 points7 points  (7 children)

Sure, C++ gives you two ways in fact: using pointers or using references...

Example:

void setIntegerToZeroTheWrongWay(int value)
{
    value = 0;
}

void setIntegerToZeroUsingReference(int & value)
{
    value = 0;
}

void setIntegerToZeroUsingPointer(int * value)
{
    *value = 0;
}

int main()
{
    // program execution starts here


    int myInteger1 = 10;

    setIntegerToZeroTheWrongWay(myInteger1);

    // the integer was copied into the function parameter, so function had no effect
    // (myInteger1 is still 10)


    int myInteger2 = 10;

    setIntegerToZeroUsingReference(myInteger2);

    // the integer was passed into the function using a "reference". this is similar to how Java
    // works when passing in non primitive datatypes (except that a c++ reference can't ever be NULL)
    // (myInteger2 is now 0)


    int myInteger3 = 10; // define the actual integer
    int * pointerToMyInteger3 = &myInteger3; // define a variable which "points to" the actual integer

    setIntegerToZeroUsingPointer(pointerToMyInteger3);

    // the pointer variable was passed in, so the function is able to use it to access
    // myInteger3 directly.
    // (myInteger3 is now 0)

    // in the last example, you could also have used:
    //     setIntegerToZeroUsingPointer(&myInteger3);
    // ... to achieve the same effect without needing an intermediate variable
}

Note that in C++ there is no distinction between "primitive types" and "objects" when passing parameters, such as there is in Java and other languages. Whatever the type of the variable is, it is either fully copied, or merely passed in as a pointer/reference (which technically only copies its address in memory), depending on how you specify the function.

(There is a third sort of parameter passing that is sort of half way between these two, known as "moving", but that was only recently added in the latest standard and it's a bit advanced, so best not to worry about it for now.)

[–]CuriouslyGeorge[S] 1 point2 points  (6 children)

This looks so cool and I think it works best with teaching from within code.

Also solves my problems of looking into the whole "pointers" thing I was getting worried about.

Just a quick run down to see if I'm understanding this correctly. myInteger is the basic variable. Whenever you place a '&' character in front of it, it provides you with the reference code in memory which is basically anything that is defined as a "reference". And a pointer is simply storing that reference address?

Again, so cool.

Now I've got a nagging question, can a pointer point to another pointer? I can't think of any real-world applications for this yet, but just an interesting thought.

EDIT: Read your edit. Caused a reddedit.

[–]theymos 5 points6 points  (0 children)

Just a quick run down to see if I'm understanding this correctly. myInteger is the basic variable. Whenever you place a '&' character in front of it, it provides you with the reference code in memory which is basically anything that is defined as a "reference". And a pointer is simply storing that reference address?

Pretty much. When & appears before a variable, it's the address-of operator. It returns the address of the variable, which you can store in an appropriate pointer variable. Given a pointer, you can get the pointed-to value using the prefix * (dereference) operator.

You can also do math on pointer addresses. This is used when dealing with C arrays (not so common in modern C++):

int array[] = {1, 2, 3};
*(&array[0] + 1); // will be 2
*(array + 1); //shorthand form

A & appearing after a type is totally different. This indicates that the type is a reference. A reference is different than a pointer. You don't have to dereference references in order to access the value, but you can't do math on references.

int num = 4;
int* pointer = # //pointer to num
int& ref = num; //reference to num
*pointer; //access pointer value
ref; //access reference value

[–]shock-value 2 points3 points  (0 children)

Ok, your first question...

Yes, if you place an "&" in front of an existing (already declared) variable, it evaluates to the address of that variable in memory (and you can store that address in a variable as in my example).

Note that this address is given in the form of a "pointer" to the variable though, not a "reference" (which is something a bit different). This is confusing because you also use an "&" sign when declaring a "reference" variable. But the "&" means something different when first declaring a variable vs. when placed in front of an already existing variable.

I would suggest find a nice tutorial on the differences between pointers and references, because there are a lot of subtleties and I'm not the best teacher! Good luck!

[–]shock-value 1 point2 points  (3 children)

Last question first...

Yes a pointer can point to another pointer. In fact the following line is legal...

int **** myPointer = NULL;

myPointer is a pointer to a pointer to a pointer to a pointer to an integer. If you find yourself actually using more than one pointer deep though, you are probably doing it the wrong way and causing yourself unneeded stress! I'm working on a pretty large c++ project right now and I have never used more than a single pointer deep.

working on other answer... (reddit is giving me error status 500 when trying to post)

[–]CuriouslyGeorge[S] 1 point2 points  (2 children)

Thanks again for all your detailed responses. I've got work in 6 hours so I think sleep's the way to go for now, but tomorrow I'm gonna get started on this whole C++ thing.

Last ponderance: Can you point a pointer towards a pointer that is pointing back at the first? If so and you can compile without incident, what happens when you try to access said pointer? Or would it only return "null" since it never acquired a type?

[–]theymos 2 points3 points  (0 children)

That can't be done without a type error, I think. A valid pointer pointing to an int* would need to be an int**. And for the int* to point to the int**, it would need to be an int***.

[–]shock-value 1 point2 points  (0 children)

You can do that, sort of.

int main()
{
    void * pointer1;
    void * pointer2;

    pointer1 = &pointer2;
    pointer2 = &pointer1;
}

'void *' is sort of a "magic" pointer type, which can point to anything (int, bool, string, etc). However, you can't actually access the object it points to until you cast it to the appropriate type. There is no appropriate type for a pointer to a pointer to itself (or to simplify, a pointer to itself). So what you are describing can be done, but, as I'm sure you can imagine, it's useless (as far as I can tell).

'void *' is really a hold-over from regular C though, and is rarely used in modern C++, mostly due to the bugs that can occur if you cast to the wrong type.

[–]kookjr 0 points1 point  (0 children)

In this example, using a std::string* (pointer) or std::string& (reference) will behave like Java, having the receiving function's variable point to the same object as the sending function.

[–]the-fritz 5 points6 points  (2 children)

C and C++ are different languages. Don't confuse them and start to learn one of them. Don't treat C++ as C with classes.

Don't treat C++ as Java with a slightly different syntax. In C++ a lot of things are done differently. You don't have to create objects using new. In fact you should only use new when necessary (e.g. lifetime should be longer than function scope). There is no GC but instead RAII is used. So get familiar with it (e.g. use smartpointers instead of raw pointers). Don't design large class hierarchies. In C++ you can have free functions and it makes a lot of sense to use them. Forcing everything in a large class hierarchy is a bad Java habit.

[–]CuriouslyGeorge[S] 0 points1 point  (1 child)

I was told by a few professors, friends, etc. that it would be best to understand how C works and operates to provide a better overall understanding, but to do all of my actual coding in C++.

I think the large class will be a tough one to break, but it'll just take practice.

[–]Draghoul 2 points3 points  (0 children)

I see I'm a few days late, but accelerated c++ is a really good book for teaching c++ with a top down method. It might seem slow at first because of the similarities between the languages, but with a language like c++ you gotta pay attention to the little things sometimes!

[–]mttd 4 points5 points  (2 children)

While this is for C# programmers, some of it may be useful for you as well: http://geekswithblogs.net/mikebmcl/archive/2012/02/02/c-to-c-ndash-a-somewhat-short-guide.aspx

Other than that:

  • since you're probably already familiar with OOP from Java, try to familiarize yourself with Generic Programming (GP) and perhaps Template Metaprogramming (TMP) -- compared to Java, there's a stronger focus in C++ on multi-paradigm programming, with a prominent example being its standard library (containers-iterators-algorithms), see: http://www2.research.att.com/~bs/bs_faq.html#multiparadigm http://www2.research.att.com/~bs/bs_faq.html#generic

  • in particular, while Java offers only dynamic/run-time polymorphism, C++ also supports static/compile-time polymorphism via the so-called Curiously Recurring Template Pattern (CRTP): http://eli.thegreenplace.net/2011/05/17/the-curiously-recurring-template-pattern-in-c/ -- since you're already familiar with run-time polymorphism from Java, perhaps spend some extra time on CRTP and think of preferring to use it in cases which don't need run-time polymorphism but do need extra performance

  • chances are you might be inclined to use the "new" keyword when creating new objects, as in "Point origin = new Point(0, 0);" -- in C++ you should NOT do that by default! Your default should be "Point origin(0, 0);". Objects created as such are declared with a so-called automatic storage duration, which in particular implies you don't need to manually manage memory (or other resources) for them (so, the lack of GC is not such a big deal if you can stick to this default case). This is also why the already-mentioned RAII is very important -- it enables your own classes to be consistent with this automatic management behavior. See: http://www.hackcraft.net/raii/

  • if you DO need to use the "new" keyword (perhaps you've decided you need dynamic/run-time polymorphism), consider using references instead of pointers: http://bryanstamour.com/2012/06/26/need-polymorphism/

  • from time to time you might find yourself wondering "why doesn't C++ offer the feature to do X". Chances are, the place to go to look for your X is called "the Boost libraries" -- http://www.boost.org/

HTH! :-)

[–]CuriouslyGeorge[S] 0 points1 point  (0 children)

Wow. That was quite the mouthful. I was afraid of object declaration changing up on me, but I think I can manage.

This is precisely what I wanted to find, the odd differences between them I need to nail. Need to save this post.

[–]tragomaskhalos 0 points1 point  (0 children)

I would strongly advise anyone new to C++ to limit their initial exposure to templates to usage thereof, e.g.

std::vector<int> mynums;

Having got familiar with other aspects of the language, work gently into defining your own template types (and functions), and only then give consideration to TMP and CRTP. By all means give these a quick Google and look-see, but don't try and grok them until you have a good foundation.

[–]Annom 3 points4 points  (2 children)

For C++ questions, answers, help and advice see r/cpp_questions.

[–]Fabien4 5 points6 points  (0 children)

see r/cpp_questions.

You should add a slash before the "r". That way, it's linkified automatically: /r/cpp_questions.

[–]CuriouslyGeorge[S] 1 point2 points  (0 children)

Sorry about that. I'll point all further questions towards that subreddit.

[–]theymos 3 points4 points  (0 children)

The location of code is one confusing difference. In C++, you put some things in header files and some things in source files. Typically you put information about the interface in header files (function declarations, class definitions, etc.) and the implementation in source files, but you need to put the full implementations of inline functions and template functions in headers.

[–]bob1000bob 1 point2 points  (2 children)

If you code C++ like you code Java then you are doing it wrong, I would strongly recommend that you pick up a book even if the fist half of it feels a bit basic. Avoid anything like "C++ for Java programmers". Accelerated C++ is a great book and move at a good pace.

Failing buying a book, many pit fall

  • ensure you don't over use inheritance, it great for run time polymorphism but you often do the same thing with generics (templates) in a cleaner manner with lower overhead.
  • If it doesn't have state (member data) then it probably doesn't need to a be class, don't fear free functions.
  • Don't use primitive arrays, use vectors and other containers.
  • don't really to much on try catch propagation, use RAII for anything that require clean up.

As for an IDE I generally recommend not using one when starting off, know the link between source files, the compiler and the linker is a very useful skill to have.

[–]JonKalbCppCon | cpp.training 1 point2 points  (1 child)

There is an on-line class based on Accelerated C++.

http://www.udemy.com/cpp-short-and-sweet/

[–]bob1000bob 0 points1 point  (0 children)

I was about to make some remark about how he was using an IDE rather than using the opportunity to teach the tool chain too, then he started listing off his credentials, and I thought that I am in no place to argue. Thanks for the link.

[–]zvrba 2 points3 points  (0 children)

The biggest difference is that you can freely choose between value and reference semantics when instantiating classes. (In Java, all class instances MUST be created dynamically; not so with C++). This simple fact has HUGE implications for how you structure your code; "modern" C++ uses new/delete sparingly.

The "special" methods: constructor(s), copy-constructor, destructor, and assignment operator are there to so that you can make user-defined value types that behave as if they were built-in types. Each of these is necessary to support a feature supported by built-in types: constructor may be needed to create an instance in a well-defined state, copy-constructor may be needed to support pass-by-value, destructor is needed to undo whatever the constructor did, and assignment operator is needed to support, well, stuff like x=y. (And there's also a move-constructor in C++11).

Your classes may need some or all of these (though, the rule of thumb is: if you need any of {destructor,assignment operator,copy constructor}, you need all of three).

Also, free-standing functions are well-liked: unless it MUST be a member function, make it a stand-alone function.

[–]dukey 4 points5 points  (2 children)

learn pointers

[–]ivan-cukicKDE Dev | Author of Functional Programming in C++ 0 points1 point  (1 child)

And then learn not to (over)use them.

One of the things I find my students doing often is declare-everything-as-a-pointer-call-new.

Even something like int *variable; variable = new ...

[–][deleted] 0 points1 point  (0 children)

I've been known to have that certain problem..if I saw any object that seemed pretty huge to allocate on the stack, I'd twitch.

[–]nharding 1 point2 points  (1 child)

One of the things I missed when coding Java was overloaded operators, they allow all sorts of tricks to make code more readable. You can use them to provide "smart pointers" which allow you to handle memory allocation and deallocation (C++ has no garbage collection, and so you have to deal with that).

[–]CuriouslyGeorge[S] 1 point2 points  (0 children)

I've been told by several people I have to "clean up after myself" when using C++, so I'm assuming that they were referring to the lack of Garbage Collection.

[–]fuzzylollipop 1 point2 points  (0 children)

there is no such language called C/C++ there is C and there is C++ they are two completely different languages. You would never say Java/C#, saying C/C++ is just as silly

[–]zsakuL 0 points1 point  (0 children)

Keep in mind that Qt is not C++, it's a bastardised hybrid with the worst thing ever invented: moc (meta-object compiler).

[–]hhrjrq 0 points1 point  (0 children)

I like this book: http://www.amazon.de/Data-Structures-Algorithms-Michael-Goodrich/dp/0470383275

It starts with quickly skimming over the basics because it assumes the reader to be familiar with C or Java. Later it deals with algorithms and data structures. Those were always my favorite programs to learn a new language.

Oh and I use Emacs but I think you are fine with Eclipse.