Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Gotchas When Learning C++, If I came from PHP/Java?

I need to learn C++ in order to learn building Nokia WRT and or maemo application. I need to know what gotchas and what aspect of C++ that I need/have to learn or focus more. One thing I got in my mind is that C++ doesn't have garbage collector. Therefor, I need to focus on variable type. But, is there any others that really important and I can't ignore it?

like image 437
ariefbayu Avatar asked Nov 29 '22 06:11

ariefbayu


1 Answers

Main gotcha is to try to envisage C++ in terms of how it differs from PHP or Java.

Sorry, it just doesn't work like that. C++ differs from those languages in almost every important respect beyond the syntax for arithmetic. Sometimes the differences are subtle. You need to learn it fresh, and not think that something that's appropriate to do in PHP or Java will work well for you in C++.

That said, common difficulties include:

  • resource management: RAII; implementing copy constructors, destructors and operator=; avoiding having to implement copy ctors, dtors, operator=.
  • understanding what references, pointers, values and automatic variables are.
  • avoiding undefined behaviour (myarray[i] = i++; is a favourite). PHP and Java are both more "tightly" defined languages than C++: firstly the behaviour of a program is more likely to be defined and hence reliable. Because of this, separate implementations are more similar than C++ implementations. It's pretty easy to write a program in C++ that doesn't just do the wrong thing, it does wildly different things on different runs, including crashing, corrupting data, etc.
  • learning to safely and effectively use templates, multiple inheritance, operator overloading, and other features you're not familiar with.
  • correct idioms for throwing and catching exceptions (throw by value, catch by reference, don't throw out of a destructor).
  • writing portable code (understanding the difference between what the standard guarantees, and what isn't guaranteed but that your implementation happens to do. implementation-defined behavior such as the sizes of fundamental types).
  • C++'s standard libraries are limited compared with Java or PHP. You will be using non-standard libraries as well. For instance, Maemo uses GTK+ and/or Qt. Often the answer to "how can I do X in C++" is, "you can't do it using only standard C++, you need platform-specific APIs or a portable library compiled for your system". X can be graphics, sockets, regular expressions, multi-threading, XML handling, crypto. Especially with mobile platforms you need to keep an eye on OS versions, things can and will change under you from time to time.
like image 138
Steve Jessop Avatar answered Dec 05 '22 08:12

Steve Jessop