Most people who have learnt computer programming know C/C++. As a relative of C, C++ has very similar syntax but more powerful features. This article mainly talks about some different parts of C++ and C with some basic syntax.
The Difference of C and C++
C is a procedural programming language thus does not support classes and objects while C++ is a combination of procedural and object oriented programming language(OOP). In a word, you can regard C++ as a hybrid language of C.
If you are a C fan but did not use C++ in the past, you can simply change you file extension to .cpp and use g++ to compile it. C++ is compatible with C in most cases.
1 | $ g++ -o <output_name> <sourcefile_name>.cpp |
Note: .C, .cc, .cpp, .c++, .cp, or .cxx are all C++ source files suffixes; header files have suffixes like: .h, .hpp, .hh. The reason why C++ has so many suffixes is just about conventions. Most commonly used suffixes are .cpp and .hpp.
Basic Syntax
In this part, I only talk about some important syntax which is different from C, if you would like more details please refer to C++ reference documents or textbooks like “C++ primer”.
Hello World
The hello world C++ file example is:
1 |
|
Note: Namespace is the mechanism for putting names defined by a library into a single place. Namespaces help avoid inadvertent name clashes. The names defined by the C++ library are in the namespace std.
Class
In C++ we use classes to define our own data types. A class defines a type along with a collection of operations that are related to that type. The class mechanism is one of the most important features in C++. In fact, a primary focus of the design of C++ is to make it possible to define class types that behave as naturally as the built-in types.
Here is an example of a class of Complex number.
1 | class Complex { |
Dynamic Memory Allocation
In C, we usually use malloc, calloc to allocate memory. However, in C++, we have new stead.
1 | // *********** C syntax *********** |
Const
we use const to define constant in C++. For example:
1 | const int M = 20; // constant M is an int |
Function Template
Say that you want to define a function to sway two variables, you may find writing similar functions for different types annoying. C++ has provided you a new feature called template thus you can write a function once for all types. Here is the example:
swapping:
1 | template <typename SWAP> |
Use C and C++ Together
In most cases, you can use C syntax in C++ files, but sometimes you will find some errors. This might be solve by adding:
1 | extern C { |
Your can refer to this link to find out: In C++ source, what is the effect of extern “C”?