Differences and Connections Between C and C++

Click the blue text
Differences and Connections Between C and C++
Follow us

Due to changes in the public account’s push rules, please click “View” and add “Star” to get exciting technical shares at the first time

Source from the internet, please delete if infringing

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 expansion of C, and it provides backward compatibility with C. It is not wrong to say that C++ completely includes C.

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 expands on the basis of C language with object-oriented features and mechanisms such as classes. However, after several revisions and many evolutions, it eventually formed the large programming language that supports a range of significant features today.

Differences and Connections Between C and C++

1. C is a procedural language, while C++ is an object-oriented language

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

(1) Differences between procedural and object-oriented programming

Procedural programming: Procedural programming analyzes the steps to solve a problem and then implements these steps one by one. When using it, each step can be called in sequence.

Object-oriented programming: Object-oriented programming decomposes problems into various objects. The purpose of establishing objects is not to complete a step but to describe the behavior of a certain thing in the entire problem-solving process.

Differences and Connections Between C and C++

(2) Advantages and disadvantages of procedural and object-oriented programming

Procedural language

Advantages: Performance is higher than object-oriented because calling classes requires instantiation, which is more resource-intensive; for example, microcontrollers, embedded development, Linux/Unix generally adopt procedural development, where performance is the most important factor.

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

Object-oriented language

Advantages: Easy to maintain, reuse, and extend. Due to encapsulation, inheritance, and polymorphism in object-oriented, low-coupling systems can be designed, making systems more flexible and easier to maintain.

Disadvantages: Performance is lower than procedural.

Differences and Connections Between C and C++

2. Specific differences between the languages

1. Different keywords

C has 32 keywords;

C++ has 63 keywords;

2. Different suffixes

C source file suffix is .c, C++ source file suffix is .cpp. In VS, if nothing is provided when creating the source file, the default is .cpp.

3. Return values

In C, if a function does not specify a return value type, it defaults to 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 defaults to receiving any number of parameters; but in C++, due to strict parameter type checking, a function without a parameter list defaults to void and does not accept any parameters.

5. Default parameters

Default parameters are values assigned to function parameters when declaring or defining a function. When calling the function, if no actual parameters are specified, the default value is used; otherwise, the specified parameters are 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 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 functional functions with the same name in the same scope. The parameter lists (number, type, order) of these functions must differ, while the return types can be the same or different. This is commonly used to handle similar functional problems 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 determines that C does not have the concept of function overloading. In contrast, C++ generates function symbols considering the function name, number of parameters, and parameter types. It is important to note that the return value type cannot be used as a basis for function overloading, meaning that int sum and double sum cannot be overloaded!

Our function overloading is also a form of polymorphism, which is called static polymorphism.

Static polymorphism: function overloading, function templates

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

When using overloading, it is essential to pay attention to scope issues: please see the following code.

Differences and Connections Between C and C++

I defined two functions in the global scope. Since they can form overloads due to differing parameter types, the main function can correctly call each respective function.

However, please look at the commented-out line in the main function. If it is uncommented, it will raise a warning: converting from double to int may lose data.

This indicates that our compiler called the function with parameter type int for both of the following calls. Thus, it can be seen that the compiler prioritizes searching in the local scope when calling functions. If it finds a match, it will call that function according to its standard. If not found, it will then search in the global scope.

Summary: C does not have function overloading, while C++ determines overloading based on function name, number of parameters, and parameter types, which is static polymorphism and must occur in the same scope to be considered 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, which cannot be used as array indices. However, in C++, variables modified by const can be used as array indices, becoming true constants. This is an extension of const in C++.

const in C: After being modified, it cannot be a left value, can be uninitialized, but cannot be re-initialized afterwards. It cannot be used as an array index, but can be modified through pointers.

In simple terms, its only difference from ordinary variables is that it cannot be a left value; otherwise, it is the same.

const in C++: A true constant. It must be initialized at the time of definition and can be used as an array index. The compilation rule of 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 may degenerate into C pointers. For example:

Differences and Connections Between C and C++

At this point, a is just an ordinary C constant variable and can no longer be used as an array index. (It references a value that is uncertain at compile time)

const generates local symbols when generating symbols. That is, it is only visible in this file. If it is necessary to use it in other files, declare at the beginning of the file: extern const int data = 10; this way the generated symbol is a global symbol.

Summary: const in C is called a read-only variable; it is just a variable that cannot be a left value. const in C++ is a true constant, but it can also degenerate into a C constant, generating local symbols by default.

Differences and Connections Between C and C++

8. References

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

References are essentially the same as pointers at a lower level, but their characteristics in the compiler are completely different.

Differences and Connections Between C and C++

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

Differences and Connections Between C and C++

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

Having understood 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 look at how to modify using references:

We see that the method of modifying the value of a is also the same, also dereferencing. However, there is a difference when calling: when calling p, *p is needed to dereference, while b can be used directly. From this, we deduce that a reference is dereferenced when used directly. The pointer p is its own address when used directly.

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

Differences and Connections Between C and C++

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

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

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

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

So what does &array mean? int ** type, is it used to point to the address of array[0]? Don’t assume it, &array is the entire array type.

To define an array reference, according to the small trick above, let’s write the array pointer first:

int (*q)[10] = &array

Now replace the & on the right with *:

int (&q)[10] = array;

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

Through the above detailed explanation, we know that references are essentially taking addresses. Now we all know that an immediate value has no address, that is:

int &b = 10;

The code cannot compile. But if you want to reference an immediate value, it is not impossible:

const int &b = 10;

By using const to modify this immediate value, an intermediate variable is generated to hold this data, so it naturally has an address to take.

Differences and Connections Between C and C++

9. malloc, free & new, delete

This question is very interesting and also a key point that needs attention. malloc() and free() are functions in the standard library for dynamically allocating and releasing memory in C. In contrast, new and delete are operators and keywords in C++. Under the hood, new and delete still call malloc and free. 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 also requires type conversion. new does not require size because it can determine from the given type, and can also assign an initial value simultaneously.

Differences and Connections Between C and C++

3) malloc is unsafe and requires manual type conversion; new does not require type conversion.

4) free only releases space; delete first calls the destructor and then releases space (if needed).

5) new first calls the constructor and then allocates space (if needed).

6) Handling methods differ when memory is insufficient (allocation fails).

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

7) new and malloc allocate memory in different locations.

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

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

new is implemented using malloc(), while malloc cannot call new.

10. Scope

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

Namespace refers to namespace. When we define a namespace, we are defining 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, if we want to use data elsewhere, we need to declare at the beginning of the file: using Myname::data; this way data will use the value from Myname. But doesn’t that mean we have to declare every symbol? Isn’t that exhausting?

Differences and Connections Between C and C++

We just need to use using namespace Myname; to import all symbols.

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

Can you learn C++ directly without learning C?

Theoretically, it is not necessary to learn C before learning C++, but having a foundation in C often provides an advantage when learning C++, at least in the part of “procedural programming”.

If you are over 18 and find learning C too difficult? Want to try other programming languages? Then I recommend you learn Python. Currently, a Python zero-based course worth 499 yuan is available for free, limited to 10 places!



▲ Scan the QR code - Get it for free

Differences and Connections Between C and C++
Click to read the original text to learn more

Leave a Comment