C++ killed my grandpappy - Is C++ hard and where are the C++ coders hiding?
After learning BASIC and ASM, for a job I started coding in C, when Hello World on Windows was 92 lines of code. (Apparently Hello World is easier now, says Pete Brown)
One of my first big projects was an app called Foolproof that kept kids in high school from breaking into their school's lab computers. It had a C core engine, a TurboVision DOS component and a 16-bit Windows C++ App. I did the DOS, Win16 and later the Win32 API all in C++. Later I did some VB3, then Delphi, then worked at Nike doing Java (right when RMI was starting, and HotJava when we wrote once and debugged everywhere) until I finally ended up in managed code, mostly doing C#.
Some folks don't know Microsoft has a free C++ Express Edition of Visual Studio 2010 and that it's one of the most used free versions out there. Someone is coding C++, and they are doing a lot of it.
Are you coding in C++, Dear Reader? What are you doing?
Most "managed people" cringe at the idea of using C++, thinking it's perhaps a language of the past and that it's not even possible to write Windows Apps in C++ without a Master's Degree. ;)
However, I just noticed there's a new project called Hilo with source to show people how to use the shiny new things in Windows 7 from C++ and how to make modern Windows applications that have animations and magical stuff that managed people assume belongs only to them.
The first drop of "Hilo" is apparently the first of many, all moving towards building a larger application. This first sample is a content browser (touch enabled!) for looking at videos and photos (yeah, yeah, I know) but you could totally use it to browse other stuff or use it as underlayment for your own app. This from the Windows Team Blog:
The main technologies used in Hilo: Direct2D, Windows Animation Manager, Windows Touch, Libraries and the Shell API.
- Direct2D: For high performance and high-quality rendering of graphics.
- Windows Animation Manager: To give the application a unique personality and to improve the user experience.
- Windows Touch: To provide a more natural user interface through which the user can just “point” and “do”.
- Libraries: To enable the application to provide users with a single, coherent view of their files.
- Shell API: To navigate the images, to optimize by using the pre-built thumbnail cache and also to provide icons from actual content.
Even if you're not going to start coding C++, it's always a good idea to "see how the other half lives." For me, it's a return to what I thought I knew, and a way to look at C++ with fresh eyes.
What surprised me was that this app was written against Windows itself, with no frameworks. I always assumed you kind of needed MFC or some other library to be productive.
I'm not sure why I remember it this way, but C++ always made me think of regular expressions, and I assumed my code would **be &all like->this.you~know? You do need to know more about Windows, to be sure, as there is likely a decade of managed programmers who have forgotten what a message pump is, but it wasn't as scary as I had remembered.
Just download C++ Express, then the Hilo source, and build it. It has some cool effects with the carousel, like inertia when it spins, scaling, Z-ordering, hardware graphics acceleration. Now all they need is a designer! ;)
As an interesting example, it uses Direct 2D and has an animation for the orbit of the carousel. I removed all the if (SUCCEEDED(hr)) code from this snippet below because that's still the one thing about C++ on Windows that irks me. Don't judge then, judge me for yanking it for brevity.
This source is extremely defensive, dutifully checking HResults at every step. I mean, seriously, if it doesn't Succeed, what are you going to do about it? If (NOTSCREWED(hr)), you know.
For this source, the salient point is that there's some nice high-level Animation constructs like timers, transitions and storyboards. For some wrongheaded reason I thought it'd be a pile of math so I was pleasantly surprised.
HRESULT OrbitAnimation::Setup(D2D1_ELLIPSE targetEllipse, double targetOpacity, double duration)
{
HRESULT hr = S_OK;
// Animation objects
ComPtr<IUIAnimationManager> animationManager;
ComPtr<IUIAnimationTimer> animationTimer;
ComPtr<IUIAnimationTransitionLibrary> transitionLibrary;
ComPtr<IUIAnimationStoryboard> storyboard;
// Transition objects
ComPtr<IUIAnimationTransition> centerXTransition;
ComPtr<IUIAnimationTransition> centerYTransition;
ComPtr<IUIAnimationTransition> radiusXTransition;
ComPtr<IUIAnimationTransition> radiusYTransition;
ComPtr<IUIAnimationTransition> opacityTransition;
// Initialize animation variables if necessary
if (nullptr == m_centerX)
{
hr = Initialize(targetEllipse, targetOpacity);
}
// Retrieve animation objects
hr = AnimationUtility::GetAnimationManager(&animationManager);
hr = AnimationUtility::GetTransitionLibrary(&transitionLibrary);
hr = AnimationUtility::GetAnimationTimer(&animationTimer);
// Initialize storyboard
hr = animationManager->CreateStoryboard(&storyboard);
// Create one transition for each orbit variable
hr = transitionLibrary->CreateLinearTransition(duration, targetEllipse.point.x, ¢erXTransition);
hr = storyboard->AddTransition(m_centerX, centerXTransition);
hr = transitionLibrary->CreateLinearTransition(duration, targetEllipse.point.y, ¢erYTransition);
hr = storyboard->AddTransition(m_centerY, centerYTransition);
hr = transitionLibrary->CreateLinearTransition(duration, targetEllipse.radiusX, &radiusXTransition);
hr = storyboard->AddTransition(m_radiusX, radiusXTransition);
hr = transitionLibrary->CreateLinearTransition(duration, targetEllipse.radiusY, &radiusYTransition);
hr = storyboard->AddTransition(m_radiusY, radiusYTransition);
hr = transitionLibrary->CreateLinearTransition(duration, targetOpacity, &opacityTransition);
hr = storyboard->AddTransition(m_opacity, opacityTransition);
hr = AnimationUtility::ScheduleStoryboard(storyboard);
return hr;
}
I was also pleased to see that intellisense worked nicely for everything typed as well as -> deferenced pointers, as seen in the screenshot below. Call me an intellicrack addict or weak-minded but it does speed things up once you know what you're looking for. The C++ Express SKU was a small download as well.
I'm not saying it's all puppies and cotton candy, but it's not the post-apocalyptic-Where-is-John-Connor-wasteland I thought it would be. I'll be giving C++ another look as I aim to learn (or relearn) another programming language this year (along with Scala). I'll report back as this application gets bigger and more interesting.
Related Links
- Developing C++ Applications for Windows 7
- Chapter 1: Introducing Hilo
The first Hilo sample application—the Hilo Browser—implements a touch-enabled user interface for browsing and selecting photos and images. - Chapter 2: Setting up the Hilo Development Environment
This article outlines how to set up a workstation for the development environment so that you can compile and run the Hilo Browser sample application. - Chapter 3: Choosing Windows Development Technologies.
This article describes the rationale for the choice of the development technologies used to implement the Hilo applications. - Windows Developer Application Gallery
- Visual C++ blog post
- Windows Team blog post
- Jason Zander’s blog post
- Project Hilo page on CodeGallery
- Project Hilo on Twitter
- Pete Brown
About Scott
Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.
About Newsletter
Great blog post ! My C++ experience was with C++ Builder in a long time ago in college working with several types of devices (Computer Engineering). After this I develop a lot of applications with VB6, then Java and later C#, that I love most.
In the company I work in Brazil there is an outsourcing company that uses Visual C++ to create photogrammetry and transportation applications. They use primarily MFC along with different self-develop libraries to work with large TIFF files. In some applications DirectX is used.
I think there are some points where C++ is necessary. Can you open a 1GB TIFF file using .NET Image class? No way (OutOfMemoryException). :-)
One example is the limited number of .NET collections that are available. .NET 4.0 helps somewhat, but is still blown away by the C++ stdlib/stlport. A couple of libraries have attempted to fill the gap (PowerCollections and C5), but neither of them are universally accepted.
Another example is the extremely powerful (Turing-complete) metaprogramming available through templates. Most C++-turned-C# users never understood or used the true power of C++. (Note that Microsoft's C++ compiler was a running joke among C++ programmers until Herb Sutter turned them around... well after .NET was released). T4 templates are a step in the right direction, but still do not achieve the power of C++ templates (in particular, automatic template instantiation based on usage).
A final example is RAII. Most of the "pitfalls" of C++ from a managed developer's perspective (i.e., deleting pointers) were replaced wholesale by RAII in the mid-90's. Really, any C++ developer after 2000 who wrote "delete" had no idea what they were doing. Sorry, but all those folks who "heaved a big sigh of relief that they wouldn't have to do explicit memory management any more" didn't know that they already didn't have to do explicit memory management! RAII is one of the most powerful idioms ever created; it enables truly rock-solid programs with a minimum of effort. The managed garbage collector actually makes RAII much more of a pain in the neck, making writing rock-solid programs much more difficult.
Re: "if (SUCCEEDED(hr)) ...", half agree here, I use (for example) "ASSERT_HR(animationManager->CreateStoryboard(&storyboard));" which will give me an assert failed dialog with the expression and HRESULT value, or "RETURN_FAILURE(expr)" which just returns the failing HRESULT. I've thought about throwing a HResultException, but it never seems any better than just C-style checking the value.
What I mean is, what, 60%+ of your C++ code is memory management (as a rule)? That is overhead. That is wasted keystrokes (as you, Scott talked about a while back - where do you want to invest your keystrokes?). So the point is, C# can do absolutely everything that C++ can do, but still be easy to use (by leveraging managed code, when you can) - plus you have the whole .NET Framework.
So although some people may prefer C++, I think it will have it's semi-permanent niche going forward - that is low-level/device driver programming. It filled a void before when there weren't options. Not that there are, I can't ever see if coming back. It's far too wordy, requires a developer to type WAY too much overhead, and it's overly-complicated, for very little/no additional benefit. That's my $.02
#define _HR(x) if (SUCCEEDED(hr)) {hr = (x);}
To write very lean, hr-safe code like:
HRESULT hr = S_OK;
_HR(AnimationUtility::GetAnimationManager(&animationManager));
_HR(AnimationUtility::GetTransitionLibrary(&transitionLibrary));
_HR(animationManager->CreateStoryboard(&storyboard));
// ... etc ...
return hr;
Also nice to have a debug version, like:
#define _HR(x) if (SUCCEEDED(hr)) {hr = (x); \
if (FAILED(hr)) { yarg(hr, #x); } }
I may have forgotten how to use cpp defines, but the idea is to be able to set a breakpoint in yarg... Or yarg can trace a log message with the hr and the stringized text of the expression x on the first failure in the method.
Nice post. This last weekend I purchased Ivor Horton's Beginning Visual C++ 2010.
Having never done C++, I wanted to learn the language. I've got a few programs running; the speed is insane compared to managed code.
I'm looking to port a few of my WPF apps to C++ and see where this leads.
Thanks for post,
Cheers,
Karl
I know its a steep learning curve but I always recommend new programmers to start with C++ because (unless you're really brave and want to get into ASM) its the lowest you're going to need to go these days.
Here is a question: chapter 3 for the hilo project on MSDN (http://msdn.microsoft.com/en-us/library/ff795785.aspx) says that hi-perf graphics programming on Windows 7 should be done in DirectX, which is made up of a set of COM-like APIs. Does this mean that COM is back in vogue? I thought when .NET was released 8 years ago the official line from MS was that COM would gradually go away; which i seriously doubted, since the entire .NET platform was built on top of COM.
VC Express is indeed quite limited (although the Win SDK will get you a lot and MFC is _not_ a silver bullet).
Managed C++ is completely up to date with modern times. Nothing like taking the bus back to the past. It's just the same as C# (unsafe?) but closer to the metal, as you like it.
> This source is extremely defensive, dutifully checking HResults at every step
It is the only way to survive in C++ professionally.
> I mean, seriously, if it doesn't Succeed, what are you going to do about it? If (NOTSCREWED(hr)), you know
If that is your stance, you might not be surprised some of the time. However you _will_ be screwed. Not all code handles 'bad input' the way you'd like it to. Really, the ultimate consequence of your thinking should be
if (S_OK!=hr)
abort();
instead of just forgetting it.
My day job involves C# and C++ development. I develop in C/C++/Obj-C for iOS.
Cheers
I think there are two legitimate reasons people prefer other languages however.
1) The library : C++ is not a "batteries included" language and thus requires finding, studying, and using 3rd party libraries to achieve many common tasks for an application. Libraries for many tasks are very high quality and easy to use, but the extra step of having to find them is a deterrent.
2) Tooling : The meta data available in managed applications makes for more powerful and easier to use development / debugging tools.
C++ is very much a core language and I doubt its going anywhere. If fact, I doubt i'd be as good at C# if i had not first cut my teeth on C++ (which is one reason I'm against using Python for introduction to programming courses).
I don't hate C++, I just hate pointers.
C# is one of the few managed languages that supports any form of RAII (with the using statement), but it falls short of doing it properly - adding more burden at the call site, and leaving more scope (pun intended) for errors. It also makes the code less readable - see this blog post.
For some examples of where memory management is more of a pain in the managed world, see this blog post
And to clean up all that error handling, read this excellent article on Enforcements from Andrei Alexandrescu.
C++ is very much alive and in productive use (we've just rewritten a major system in C++ - it was originally in .Net). It's not perfect, and suffers from some legacy from the past. I'd like to see more mainstream interest in the D Programming Language, which is spiritually what C++ would be if it had dropped source compatibility with C, and included more "modern" idioms (including many not in C#).
Oh, and personally I'd avoid MFC like the plague :-) Use WTL if you must use a MS framework - although I've not done GUI work in C++ for years.
Qt can, it's the equivalent of the .NET libraries for C++. Without Qt, I probably would have moved at least part of my coding to C# for the high-level libraries.
There's a lot there to work through. If you don't think you can do everything just start with the Coding Standards book, which rolls up a lot of the other stuff anyway.
However, as regards RAII and WinAPI - there are three options (and I wouldn't usually recommend working without once of these):
1. Use an existing wrapper/ helper framework/ library (such as WTL). Just not MFC unless you are forced to.
2. Write your own wrappers as you go. Just for the RAII bits, don't bother trying to encapsulate all the methods - you'll end up writing your own MFC otherwise. If you stick to the resource management it's not that much work - pays for itself after 2-3 calls.
3. Use generic RAII classes, such as ScopeGuard, or even Boost's shared and scoped pointers (which can manage non-memory resources too).
What is Microsoft's vision for the future of C++ and managed code?
Jeff
I'll personally switch to managed code when and only when Windows itself become managed (there is NO trace of notable managed code in Win7). And I do not see that coming any time soon - Microsoft is not that stupid, they know how problematic .net really is.
One thing I do rather miss about C++ is pointers. Yes most things in C# are technically already a reference, but I somehow found it easier to remember that when I had to manually de-reference things and pass addresses around myself. It's a good language for forcing yourself to practice good memory management, and to really think about how your classes are constructed.
You could notify the user that something went wrong, restart the program, log the error. Isn't this basic stuff that you blogged about before? Doesn't it make the code more reusable to handle errors correctly? Did I miss you meaning here?
What amazes me is that most of the coders at work think that I'm some sort of wizard because I can to something/anything productive in C/C++.
BTW, I am be coding in C++, but I try to keep my syntax simple and in the pure C range. I may have to code a few more lines but ... for me it makes my code more readable and more maintainable.
Lee
I'm a hobby programmer and I use Visual C++ Express Edition for some projects in pure win32. I don't use any MFC.
For smaller projects, I always find that frameworks just get in the way. Far simpler to overcome the learning curve once, write some reusable objects fitted to your purpose and move on. The good thing about the core API is that while frameworks come and go, the core API rarely changes - learn once, code forever :)
Here's a Sudoku program I wrote in visual C++ express edition in pure win32 (yes that's why the exe is so small, and a large part of it is the graphics)
jsiSudoku from Download.com - Visual C++ Express and pure win32
I would like to use Java simply because it has tools that run on my Mac, but Java doesn't have pointer access or a way to map a struct to memory.
I've seen enough fresh-faced youngsters who've never seen anything but C# with that perplexed look on their face that tells me they're thinking, "But I wasn't even *AIMING* at my foot!" to know that C# isn't protecting them as much as they believe it is. Just as I recommend that anybody who plans to delve into C take a look at Assembler, I recommend that anybody planning to work in C# take a look at C++. It never hurts to know what's really happening, and that knowledge will save you more often than not.
C# coding happens in time x, including debugging. No memory management bugs, decent Intellisense.
VB.NET coding happens in time 0.5x, including debugging. No case insensitivity bugs, undeniably superior Intellisense. Option Explicit On and Option Strict On wipe out whole classes of runtime and compile time programmer error bugs.
C++ coding happens in time 5x, including debugging. Oh, the mess you can make with a multi-inheritance template model... or COM. Or maybe it's just COM programming using C++; I'd much rather author COM servers in VB6 or a .NET language. I don't cringe; I've got a portfolio full of C++ COM servers, in- and out-of-process, and I came to hate it all compared to a direct-DLL/EXE or Managed approach to IPC.
(XAML coding? Time 10x, of course. Maybe Blend hides this, I dunno. Reverting to a late-bound declarative model and then gushing for four years about how much better it is without properly tooling it for developers, or documenting it at all well, made it difficult for me to take seriously. I hate getting HRESULT crashes at runtime, but only on test machines, and that ".toolbox" thing makes me wonder if I'm about to play a video game.)
Objective-C? Maybe 2x. The lack of a memory manager in Apple's stuff is aggravating, but at least its framework has been documented effectively, its models and patterns have been around for 25 years, and it doesn't suffer from absurd half-endorsed "open source" framework extension bloat and rug-ripping new-language inventions every other year. And to be equally as frank, XCode 4 looks really, really good.
Oh, and Scott? That body of source code for Direct2D *is* programming against an abstraction framework. Those are marshalled in-process COM calls, there. At that point you might as well just code it up in VB or C#.
When I started to learn C++, I thought the WIN32 API was the only way to code GUIs under Windows. Because of that, I quickly hated this language.
Fortunately, I was completely wrong. There are numerous C++ GUI libraries.
WIN32 and the MFC have by far the worst APIs of those. They're not even cross-platform…
Then I discovered Boost, GTKmm, Qt, …
Finally, since several years, C++ is now my favorite programming language.
Scott, whether you can provide another rss source for users like me to subscribe.
For one, Microsoft's implementation feels overly cluttered with __DECLSPEC __WIN32 __WINNT, and whatnot. The implementation at the time was not even close to ANSI compliant (e.g. exception handlers were implemented as macros that leaked excessively) and didn't support much of the POSIX or ANSI class libraries so it was a real pain to move or reuse code across platforms. And I hate to say it, but MFC was never a real object-oriented class library--it was just a thin and clumsy wrapper around the Win32 API disguised as a class library. Maybe things have changed today, but that's the way it was back then.
I'm not really trying to bash Microsoft here since I love what they've done with C# and the .NET Framework, but the implementation of Microsoft C++ was the primary reason I decided to give up the language years ago. I tried picking up the language again last year with Visual Studio 2005/2008 and decided it wasn't worth the effort. I mean I am significantly more productive in C#, C# seems to be a much cleaner language, and I don't have to be overly concerned with ANSI/UTF-x/Unicode encoding issues or Pascal/C calling conventions.
But most C++ programmers can code their own sort functions, and more. Most C++ developer have a better understanding of basic computer science, then C# developers do.
The educational value of C++ is great. The other day , i took a presentation on how one can convert
int Add( int a , int b ) { return a + b ; } into
extern "C" int __declspec(dllexport) int __stdcall Add(int a , int b ) { return a+b; } to be exported from a DLL. I got a great standing ovation. With this simple program , i could explain extern "C" , exporting of functions , calling convention , Microsoft name mangling , Module definition file , Static linking of DLL , Dynamic Linking of DLL as well.
I found out that we can use WineLib to write Linux applications using Win API . Pls. check
my blog entry @http://praseedp.blogspot.com/search/label/WineLib
I purchased Windows via C++ by jeffrey ritcher yesterday and it was amusing to read it as well.
regards
Praseed Pai
Thanks.
#include <Windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MessageBox(NULL, L"Hello, World", L"Hello, World", MB_OK);
}
Comments are closed.