Seven Extensions of C++ Over C

Through learning C, we have understood its application in “procedural programming”. What if we want to operate on a certain type? This requires us to learn “C with classes”—C++. To understand the object-oriented programming paradigm, we must first grasp the basic concepts of object-oriented programming such as classes, objects, encapsulation, inheritance, derivation, and polymorphism, and use the object-oriented programming language (C++) to design programs. C++ is developed based on C and is compatible with it. Let us explore this powerful tool step by step:

1. Language Features:

It is essentially a tool we use.

C Language: The standard library mainly provides some basic functions, such as string manipulation, mathematical operations, input and output functions, which are relatively simple and fundamental.

C++: The standard library is even richer; in addition to including the standard library of C, it also adds many components, such as the STL (Standard Template Library), which includes containers, algorithms, and other tools, greatly improving development efficiency.

Example:

lTemplate usage in C++

l[Template usage characteristics: a variable must be defined (eg:T), T can be replaced with any data type, such as int, double, char, etc.]

l[Standard Namespace: For example, std. When using functions or objects from the standard library, the std:: prefix must be added (of course, you can also use the using namespace directive to simplify, but it may cause name conflicts).]

Seven Extensions of C++ Over C

Template Declaration template, defines a template function named MyMax that takes two parameters of type T, a and b, and returns a value of type T. The function body uses the ternary operator (a > b) ? a : b to determine and return the larger of a and b.

Using the main function to call the MyMax function, passing two int type parameters 3 and 5, and outputting the returned maximum value to the console, then line break. Similarly omitted.

2. Classes and Objects and In-depth Discussion of Classes and Objects

1. First, let’s understand what classes and objects are:

(Here we have learned about structures Structures are user-defined data types. A class represents a combination of other types, which can be understood as an extension of structures In addition to variable attributes there are member functions representing actions)

(1) A class (class) refers to a user-defined type, a general set of attributes or actions (eg: A person has five senses, a car has wheels), a class contains its members: data members (with variable attributes) and member functions (representing actions).

(2) An object (object) refers to a specific individual (eg: A Chinese person, who has brown eyes; a motorcycle, which has two wheels)

2. Now let’s delve deeper into their discussion:

(1) The relationship between the two can be understood as follows:

l A class is abstract, while an object is concrete (eg: Just like color is abstract, while red is concrete)

l An object is a variable declared by a class, representing the “real-world embodiment” of the class

3. Please think about how to implement the following example (a small test):

Example:

Application of classes and objects

1. Input and output of hours and minutes:

[C++ requires the header file for using library functions, and using the std namespace for the program to utilize this information]

[Tip: Input and output streams cin, cout are used with “>>” and “<<” respectively, which will be discussed later regarding input and output streams]

[Note: When declaring a class, its members must be specified as public or private; if not specified, they are considered private]

[When using a class, enclose its members with “{}”; at the end, add a semicolon “;” to signify the end of that part]

Seven Extensions of C++ Over C

Here, Class is a marker for declaring a class, Class Time declares the Time class, using public to declare public members (set_time(void) for setting time and show_time(void) for displaying time), and then private to declare private int type data members huor, minute, sec. In the main function, define an object t of type Time, use the output stream cout and “>>”–output operator to output the prompt “Please enter hours, minutes, seconds”, adding endl at the end to indicate a line break, which is equivalent to the commonly used “\n” in C, then call the member functions set_time and show_time of the Time type t object, and finally return 0. Define the set_time function and show_time function for the Time type, inputting and outputting huor, minute, sec. This completes the program design for the Time type t object. (This is explained in detail, and the subsequent code analysis can refer to this)

3. Inheritance and Overloading

C Language: None.

C++: First, let’s understand their meanings:

1. Inheritance: Allows a class (subclass/derived class) to be created based on another class (parent/base class), thus reusing the parent class’s code and allowing for the extension or modification of one of the core features of the parent class, allowing a class (subclass/derived class) to have additional functionality. (eg: It can be seen as a son being born from parents, inheriting the father’s genes, while also adding and modifying the mother’s genes)

2. Overloading: Refers to multiple functions/operators having the same name within the same scope, but with different parameter lists (different parameter types, counts, or orders). (eg: Just like in China, there are many people named Zihan, but their personalities, heights, and features are different)

l [This will lead to commonly used small tools “structures” which provide convenience for our program design, and can be used for initializing data members, as seen in the example]

3. Please think about how to implement the following example (a small test)

Example: Inheritance::

Seven Extensions of C++ Over C

Define a class of type Animal, with a public no-argument eat function that outputs “The animal is eating” and then uses endl to line break. Similarly, define a class of type Dog, adding the inherited Animal type as the base class after the “:”. The base class of the Animal type has “public” in front, which is called “public inheritance”. Following the parent class, use your own methods, and then in the main function, first define an object myDog of the Dog class, and then call the eat function and bark function.

Overloading:

l Comparing the size of numbers (function overloading), operator overloading can be analogized similarly

Seven Extensions of C++ Over C

The main function calls the max function twice, each time with different argument types, and the system will automatically find the matching function based on the argument types and call the corresponding function. (The program design is relatively simple; the key is to know how to accurately call max)

l Comparing the size of numbers (using constructors)

l [Constructors can initialize data members, and can be defined inside or outside the class, or use parameter initialization lists]]

l [Constructor characteristics: the name is the same as the class name, and there is no return value]

Seven Extensions of C++ Over C

In the Nums class, the public section defines the constructor Nums() { a=0; b=0; c=0; } and declares int type a, b, c in the private section. Define the set_nums function to read three integers and save them to a, b, c. Then define the mas_num function to compare a, b, c and return the maximum value. In the main function, create an object num of the Num class, output the prompt, and then call the set_nums and mas_num functions, naming the result of num mas_num for easy output.

4. Input and Output Streams and Parameter Passing

1. Input and Output Methods.

C Language: Through learning C, we know to use standard input and output functions like printf, scanf, etc., and need to include the header file , these functions are library functions, and formatted input and output are quite flexible.

C++:: Through cin, cout for input and output operations, introducing input and output streams (iostream library). Used with “>>”–output operator, “<<“–insertion operator (eg: Just like eating requires a spoon).

Example: Input your age in C language

Seven Extensions of C++ Over C

Using the header file, you can use printf for output, scanf for input, etc., to input your age.

Input your age in C++

Seven Extensions of C++ Over C

Using the header file, you can use cout for output, cin for input, etc., to input your age.

2. Parameter Passing

Both have: value passing, pointer passing (*), array passing (arr).

C Language: Can only achieve similar reference effects through value passing and pointer passing, generally cannot change the initial data..

C++:: On this basis, reference passing (&) is added, which can change the initial data, making it safer and more intuitive.

3. Please think about how to implement the following example (a small test)

Example: Reference passing (&) in C++, passing a reference instead of a value, if modified, will affect the original variable (eg: Just like in a merit evaluation table, what is passed is our name, not us; if the name is modified, it changes to another person)).

Seven Extensions of C++ Over C

Defined a swap function that takes two integers a and b by reference, swapping their values. Because it passes by reference, modifying a and b will directly affect the original variables passed when calling the function. Then define a function changeValue that takes an integer num by reference, modifying its value to 100. Similarly, modifying num will directly affect the original variable passed when calling the function.

In the main function, call the swap function to swap the values of x and y, and output the result after swapping.

Declare and initialize an integer variable number, and output its initial value.

Call the changeValue function to modify the value of number to 100, and output the modified result.

5. Exception Handling

C Language: We know that C does not have a built-in exception handling mechanism, usually indicating errors through return values or global variables (eg: errno), mixing error handling code with normal logic.

C++: Introduces an exception handling mechanism, using try, catch, and throw keywords to catch and handle exceptions. This separates error handling code from normal logic, improving code readability. (eg: Just like using bags to separate them)

1. Please think about how to implement the following example (a small test)

Example:

l Error checking in C (defining a function to determine if there is an error)

Seven Extensions of C++ Over C

Defined a function divide that takes two integer parameters a and b, and a pointer to an integer result. The return value is an integer indicating whether the operation was successful. Use if to check if the divisor b is 0. If the divisor is 0, return -1 indicating the operation failed. If the divisor is not 0, calculate the result of a divided by b and store it in the memory location pointed to by result.

l Exception handling in C++

Seven Extensions of C++ Over C

In the main function, the try block contains code that may throw exceptions. Define two int type variables a and b, where b is initialized to 0. Use if to check if the divisor b is 0. If the divisor is 0, throw an exception; if the divisor is not 0, output the result of a divided by b. Catch exceptions of type const char* thrown in the try block. After catching the exception, output the exception information.

[In summary: C indicates whether an operation is successful by returning an error code, while C++ separates error handling code from normal logic through an exception handling mechanism, making the code clearer and more powerful.]

Leave a Comment