Differences and Connections Between C and C++

Click the "Xiaobai Learns Vision" above, select "Star" or "Top"
Heavyweight content delivered promptly

Introduction

Do you fully understand the connections and differences between C and C++? After reading this article, you may gain some new insights.

Reprinted from丨C Language and CPP Programming

What is the relationship between C and C++?

First of all, C++ and C are two different programming languages, but C++ is indeed an extension and enhancement of C, providing backward compatibility with C. The statement that C++ completely encompasses C is not entirely wrong.

Differences and Connections Between C and C++

C++ was initially invented by Bjarne Stroustrup and was originally called “C with Classes”.

It is clear that it expanded on C with object-oriented features and mechanisms such as classes. However, after several revisions and evolutions, it finally formed the large programming language we know today, which supports a series of significant features.

Differences and Connections Between C and C++

C is Procedural Language, While C++ is Object-Oriented Language

We all know that C is a procedural language, while C++ is an object-oriented language. Discussing the differences between C and C++ is essentially comparing procedural and object-oriented programming.

(1) Differences Between Procedural and Object-Oriented Programming

Procedural: Procedural programming involves analyzing the steps to solve a problem and implementing these steps one by one. When needed, they can be called sequentially.

Object-Oriented: Object-oriented programming involves breaking down the problem into various objects. The purpose of creating an object is not to complete a step but to describe the behavior of a certain entity throughout the problem-solving process.

Differences and Connections Between C and C++

(2) Pros and Cons of Procedural and Object-Oriented Programming

Procedural Language

Advantages: Performance is higher than object-oriented because instantiation is required when calling classes, which incurs greater overhead and resource consumption; for example, microcontrollers, embedded development, and Linux/Unix generally adopt procedural development, where performance is the most important factor.

Disadvantages: Not as easy to maintain, reuse, or extend as object-oriented.

Object-Oriented Language

Advantages: Easier to maintain, reuse, and extend. Due to encapsulation, inheritance, and polymorphism, object-oriented programming can design low-coupling systems, making systems more flexible and easier to maintain.

Disadvantages: Performance is lower than procedural.

Differences and Connections Between C and C++

Specific Language Differences

1. Different Keywords

C has 32 keywords;

C++ has 63 keywords;

2. Different File Extensions

C source files have the extension .c, while C++ source files have the extension .cpp. In Visual Studio, if no extension is given when creating a source file, the default is .cpp.

3. Return Values

In C, if a function does not specify a return type, it defaults to returning int; in C++, if a function has no return value, it must be specified as void.

Differences and Connections Between C and C++

4. Parameter Lists

In C, if a function does not specify a parameter list, it can accept any number of parameters by default; in C++, due to strict parameter type checking, a function without a parameter list defaults to void and accepts no parameters.

5. Default Parameters

Default parameters are specified when declaring or defining a function to provide a default value for the function’s parameters. When calling the function, if no actual parameter is specified, the default value is used; otherwise, the specified parameter is used. (C does not support default parameters)

· Partial Default Parameters

Differences and Connections Between C and C++

· Full Default Parameters

Differences and Connections Between C and C++

Note:

· In the case of partial defaults, parameters with default values must be placed at the end of the parameter list.

· Default parameters cannot appear simultaneously in both the function declaration and definition; only one can be chosen.

· Default values must be constants or global variables.

· Default parameters must be passed by value or constant reference.

6. Function Overloading

Function overloading is a special case of functions, referring to declaring several similarly functioning functions with the same name within the same scope, where these functions must have different parameter lists (number, type, order), and the return type can be the same or different. It is commonly used to handle similar functionalities with different data types. (C does not support function overloading; C++ supports function overloading).

Differences and Connections Between C and C++

The rules for generating function symbols in C are based on the name, which means that C does not have the concept of function overloading. In C++, generating function symbols considers the function name, number of parameters, and parameter types. It should be noted that the return type cannot be used as the basis for function overloading, meaning that int sum and double sum cannot constitute an overload!

Our function overloading also belongs to a type of polymorphism, known as static polymorphism.

Static Polymorphism: Function Overloading, Function Templates

Dynamic Polymorphism (runtime polymorphism): Polymorphism in inheritance (virtual functions).

When using overloading, be aware of scope issues: see the code below.

Differences and Connections Between C and C++

I defined two functions in the global scope, which can constitute an overload due to different parameter types. At this point, calling them in the main function can correctly call each respective function.

However, see the commented-out line in the main function. If it were uncommented, it would raise a warning: converting double type to int may lose data.

This means that our compiler would call the parameter type int compare for both calls below. Thus, when the compiler calls functions, it prioritizes searching in the local scope; if successful, it calls the function based on that standard. If not found, it searches in the global scope.

Summary: C does not have function overloading; C++ determines overloading based on function name, number of parameters, and parameter types, which is static polymorphism, and must be in the same scope to be called overloading.

Differences and Connections Between C and C++

7. const

In C, variables modified by const are not constants; they are called constant variables or read-only variables, and these constant variables cannot be used as array subscripts. However, in C++, variables modified by const can be used as array subscripts, becoming true constants; this is an extension of const in C++.

Const in C: After being modified, it cannot be an lvalue, can be uninitialized but cannot be reinitialized afterward. It cannot be used as an array subscript and can be modified through pointers.

Simply put, the only difference is that it cannot be an lvalue; everything else is the same.

Const in C++: A true constant. Must be initialized upon definition, can be used as an array subscript. The compilation rule for const in C++ is replacement (similar to macros), so it is regarded as a true constant. It can also be modified through pointers. It should be noted that C++ pointers can degenerate into C language pointers. For example:

Differences and Connections Between C and C++

In this case, a is just an ordinary C constant variable and can no longer be used as an array subscript. (Referring to a value that is uncertain at compile time)

Const in symbol generation is a local symbol, which means it is only visible in this file. If you want to use it in another file, declare it at the file header: extern const int data = 10; this generated symbol will then be a global symbol.

Summary: Const in C is called read-only variable, which is just a variable that cannot be an lvalue; in C++, const is a true constant but may degenerate into a C constant, generating a local symbol by default.

Differences and Connections Between C and C++

8. References

When we talk about references, we immediately think of their sibling: pointers.

References and pointers are essentially the same thing at the lower level, but they behave differently in the compiler.

Differences and Connections Between C and C++

First, define a variable a = 10, then define a reference b and a pointer p pointing to a. Let’s look at the assembly to see the underlying implementation:

Differences and Connections Between C and C++

We can see that the underlying implementation is completely consistent, taking the address of a and placing it in the eax register, then storing the value of eax in the memory of reference b/pointer p. Thus, we can say (at the lower level) that a reference is essentially a pointer.

Understanding the underlying implementation, we return to the compiler. We see that modifying the value of a with pointer p is done by *p = 20; that is, dereferencing and replacing the value.

Now let’s see how to modify using a reference:

We see that modifying the value of a is also done by dereferencing. However, when we call it, there is a difference: calling p requires *p to dereference, while b can be used directly. Thus, we deduce: a reference is dereferenced when used directly. The pointer is used directly for its own address.

We also understand that the memory allocated for the reference cannot be accessed. If used directly, it is dereferenced. Even printing &b outputs the address of a.

Differences and Connections Between C and C++

Attached is a small trick for converting a pointer to a reference: int *p = &a, we move the reference symbol to the left and replace *: int &p = a.

Next, let’s see how to create a reference to an array:

int array[10] = {0}; // Define an array

We know that using array refers to the address of the first element of the array, which is of type int *.

Then what does &array mean? It is of type int **, pointing to the address of array[0]? Don’t assume; &array is the whole array type.

To define an array reference, let’s first write an array pointer:

int (*q)[10] = &array;

Replacing the & on the right with * gives us:

int (&q)[10] = array;

Testing sizeof(q) = 10. We successfully created an array reference.

From the detailed explanation above, we know that references are essentially taking addresses. Now, we know that an immediate number does not have an address, i.e.,

int &b = 10;

This code cannot compile. But if you really want to reference an immediate number, it is not impossible:

const int &b = 10;

This means that the immediate number is modified by const, which will generate a temporary variable to store this data, thus having an address to take.

Differences and Connections Between C and C++

9. malloc, free && new, delete

This issue is interesting and needs attention. malloc() and free() are the standard library functions in C for dynamically allocating and freeing memory. new and delete are C++ operators and keywords. new and delete still call malloc and free at the lower level. The differences between them are as follows:

1) malloc and free are functions, while new and delete are operators.

2) malloc requires size before allocating memory, while new does not.

For example:

int *p1 = (int *)malloc(sizeof(int)); int *p2 = new int; // int *p3 = new int(10);

malloc requires specifying size and needs type conversion. new does not require size specification because it can infer from the given type, and can also assign initial values.

Differences and Connections Between C and C++

3) malloc is unsafe and requires manual type conversion, while new does not need type conversion.

4) free only releases space, while delete calls the destructor before releasing space (if needed).

Corresponding to point 5, if complex types are used, it destructs and then calls the operator delete to reclaim memory.

5) new calls the constructor before allocating space (if needed).

Corresponding to point 4, when we call new (e.g., int *p2 = new int;), the underlying implementation is: first, push 4 bytes (the size of int), then call the operator new function to allocate memory. Since this line of code does not involve complex types (like class types), no constructor is called. Below is the source code of operator new, which is also an important function in the implementation of new:

Differences and Connections Between C and C++

We can see that malloc(size) allocates memory of the specified byte size, and if it fails (malloc returns 0), it enters a judgment: if _callnewh(size) also fails, it throws a bad_alloc exception. _callnewh() function checks if the new handler is available; if available, it will free some memory and return to malloc to continue allocation; if not available, it throws an exception.

Differences and Connections Between C and C++

6) The handling of insufficient memory (allocation failure) differs.

malloc fails and returns 0, while new fails and throws a bad_alloc exception.

7) new and malloc allocate memory in different locations.

malloc allocates in the heap, while new allocates in the free store area.

8) new can call malloc(), but malloc cannot call new.

new is implemented using malloc(), while new is unique to C++ and malloc cannot call it.

10. Scope

C has only two scopes: local and global. C++ has: local scope, class scope, and namespace scope.

Namespace refers to namespace; defining a namespace creates a new scope. Accessing it requires the following way (using std as an example)

std::cin << "123" << std::endl;

For example, if we have a namespace called Myname with a variable called data, to use data elsewhere, we need to declare at the file header: using Myname::data; this way, data will use the value from Myname. But doesn’t this mean we have to declare every symbol, which is exhausting?

Differences and Connections Between C and C++

We can simply use using namespace Myname; to import all symbols from it.

This is also the meaning of using namespace std; that we often see.

Can You Learn C++ Directly Without Learning C?

As mentioned earlier, the most important part of the C++ programming language is “procedural programming”, which is the domain of its big brother, C. Even if you haven’t learned C, jumping straight into C++ will still involve content from “procedural programming”.

Theoretically, it is not necessary to learn C before learning C++, but having a foundation in C often provides an advantage when learning C++, especially with the procedural programming part, which can be navigated easily.

Download 1: OpenCV-Contrib Extension Module Chinese Tutorial

Reply "Extension Module Chinese Tutorial" in the backend of "Xiaobai Learns Vision" public account to download the first OpenCV extension module tutorial in Chinese, covering installation of extension modules, SFM algorithms, stereo vision, target tracking, biological vision, super-resolution processing, and more than twenty chapters of content.

Download 2: Python Vision Practical Project 52 Lectures

Reply "Python Vision Practical Project" in the backend of "Xiaobai Learns Vision" public account to download 31 practical projects including image segmentation, mask detection, lane line detection, vehicle counting, eyeliner addition, license plate recognition, character recognition, emotion detection, text content extraction, face recognition, etc., to help quickly learn computer vision.

Download 3: OpenCV Practical Projects 20 Lectures

Reply "OpenCV Practical Projects 20 Lectures" in the backend of "Xiaobai Learns Vision" public account to download 20 practical projects based on OpenCV for advanced learning of OpenCV.

Group Chat

Welcome to join the reader group of the public account to communicate with peers. Currently, there are WeChat groups for SLAM, 3D vision, sensors, autonomous driving, computational photography, detection, segmentation, recognition, medical imaging, GAN, algorithm competitions, etc. (These will gradually be subdivided). Please scan the WeChat number below to join the group, and note: "Nickname + School/Company + Research Direction", for example: "Zhang San + Shanghai Jiao Tong University + Vision SLAM". Please follow the format; otherwise, you will not be approved. After successful addition, you will be invited to join related WeChat groups based on research direction. Please do not send advertisements in the group; otherwise, you will be removed. Thank you for your understanding~

Leave a Comment