You can use C++ almost immediately, as it supports most C code. Then you can slowly start using C++ features that you find are worth their cost. I use C++ this way, sticking to a subset of its features while still getting lots of benefit over C. Some C++ purists will say you're using it wrong, but they're idiots. C++ is a tool that can be used in many ways.
Perhaps the most useful feature I find in C++ is being able to define classes. Instead of this in C:
Code:
// foo.h
typedef struct foo_t {
int x, y; // don't use these directly
} foo_t;
void foo_init( foo_t*, int );
int foo_next( foo_t* );
// foo.c
#include "foo.h"
void foo_init( foo_t* f, int i )
{
f->x = i;
f->y = 0;
}
int foo_next( foo_t* f )
{
return f->x * f->y++;
}
// user.c
#include "foo.h"
void user( void )
{
foo_t foo;
foo_init( &foo, 3 );
printf( "%d\n", foo_next( &foo ) );
printf( "%d\n", foo_next( &foo ) );
}
You can do this in C++:
Code:
// Foo.hpp
class Foo {
public:
void init( int );
int next();
private:
int x, y;
};
// Foo.cpp
#include "Foo.hpp"
void Foo::init( int i )
{
x = i;
y = 0;
}
int Foo::next()
{
return x * y++;
}
// user.cpp
#include "Foo.hpp"
void user()
{
foo_t foo;
foo.init( 3 );
printf( "%d\n", foo.next() );
printf( "%d\n", foo.next() );
}
Additionally, you are gauranteed that the user isn't directly modifying x and y of Foo, since they are private. This helps a lot for ensuring that changes to the implementation don't affect any user code. The C++ code is also less-verbose, as you don't have the redunant "foo" when calling functions, and in functions, you don't have the constant f-> before member accesses (at first you might prefer it explicit, which you can do in C++ by putting this-> before member accesses, but later you'll see that it generally clutters code). Performance-wise, the above should behave the same, since the C++ version does the same thing behind-the-scenes as the C version.