Switching from C to C++

From Wikiversity
Jump to: navigation, search



Switching from C to C++
Prerequire Some understanding of C and C++
Experience Intermediate
Lesson Description
Differences between C++ and C
What you will learn
  1. How C++ is different from C


Some believe that learning C++ is easy and suggest learning C before learning C++, while other people disagree and believe that if your intention is to learn C++ that you are better off learning C++ directly rather than trying to learn C first. Switching from C to C++ can be both easy, as there are many similarities between the two languages, and hard, as there are many differences that require forgetting what you know and habits that you may have developed from programming in C.

Differences[edit]

  • C++ uses new and delete operators for memory management while C uses library functions.
  • C++ extends structs and unions, and also includes classes.
  • C++ has templates while C does not.
  • C++ has operator and function overloading.
  • C++ requires type casts conversions but C is less strict and C++ also provides alternative type conversion semantics.
  • typedef creates unique types in C++, and creates type aliasing in C.

Thinking in C++[edit]

If you are previously a C programmer and have decided to switch to C++, you should throw away some C concepts and get used to the C++/OO way of doing things:

  • C programmers tend to write lots of global functions. If these functions needs an object to work, you should make them member functions of a class.
  • You should group similar functions working with different types in a template.
  • C programmers usually prefix their identifiers to prevent name conflict. However, this is not necessary in C++ as they can be put in a namespace.
  • There are usually lots of pointers and type casts in C. However, you should use less pointers in favour of references and less type casts in favour of derived classes.
  • Think everything as objects. For example, if you write a control program for a plane, you should create a class called Plane and create functions inside it.