object-oriented programming in C++ with examples

object-oriented programming

Description:

object-oriented programming (oop) methods For relatively small-scale programs, programmers can directly write a process-oriented program that describes each program in detail. An instantaneous data structure and operation process. But when the scale of the program is large, it appears to be powerless. C++ was created to solve the difficulties in the process of writing large programs.

What is object-oriented programming?

The idea of ​​object-oriented programming (oop) is similar to the idea of ​​dealing with problems in people’s daily life. In the natural world In the world and social life, a complex thing is always composed of many parts. For example, a car is powered by an engine, It is composed of components such as chassis, body, and wheels; a house is composed of a living room, bedroom, kitchen, and bathroom; one The school is composed of many colleges, administrative departments, and student classes. When people produce cars, they do not design and manufacture engines first, then design and manufacture chassis, and then design and manufacture cars. To build the body and wheels, but to design and manufacture the engine, chassis, body, and wheels separately, and finally assemble them together. When assembling, there is a certain connection between the various parts in order to coordinate the work. For example, the driver can adjust the oil circuit by stepping on the accelerator. Control the speed of the engine and drive the wheels to rotate. This is the basic idea of ​​object-oriented programming. In order to further illustrate the problem, the following first introduces several concepts related to object-oriented programming (oop).



Objects in object-oriented programming:

Anything in the objective world can be regarded as an object. In other words, the objective world is Composed of thousands of objects. Objects can be natural objects (such as cars, houses, bears), or in social life A logical structure (such as class, Branch, Company), even an article, a graphic, a plan, etc. can be regarded as Object. The scope of objects is very wide. For example, a school is an object, a class is also an object, and a student is also an object. Objects. Similarly, a division, regiment, company, and squad in the army are all targets. The object is the basis of the system This unit. The system can be large or small, and the same object can be large or small, depending on needs. In actual social life, people It is active in different objects. For example, students in a class have a class, a meeting, Cultural and sports activities, etc.

It can be seen that when a class is used as an object, there are two elements: one is the static characteristics of the class, such as the class belongs to Tie and Major, the number of students, the classroom, etc., such static characteristics are called “attributes”; the second is the dynamic characteristics of the class, such as This kind of dynamic feature is called “behavior” in the study, meeting, sports competition, etc. If you want to control the students’ activities You can send a message to the class from the outside world (such as going to morning exercises when you hear the broadcast sound and end get out of class when you hear the bell, etc.), generally Call it “message”. Any object should have attributes (attribute)

These two elements of behavior (behavior). The object should be able to Perform corresponding operations according to the message given by the outside world. An object is generally composed of a set of attributes and a set of behaviors. A DVD player is an object. Its attributes are the manufacturer, brand, weight, volume, color, price, etc., and its behavior It is its function, for example, it can play, fast forward, rewind, pause, stop, and other operations according to the information given to it from the outside world. Generally speaking, anyone with attributes and behavior can be used as objects. A number is also an object because It has a value, various arithmetic operations can be performed on it, and its value can be output. A word can also be used as an object, it has length, Attributes such as character types can be inserted, deleted, output, and other operations. Multiple objects in a system communicate with each other through certain channels, as shown in the below figure.

object-oriented programming

To make a certain When an object realizes a certain behavior (that is, operation), it should send corresponding messages to it. For example, I want to make a DVD picture.

The machine starts to put, For example, a person must press the buttons on the DVD player, or use the remote control DVD player to send an electrical signal. Between objects, This is how they communicate with each other by sending and receiving messages. Object-oriented programming(oop) adopts this kind of thinking that people are familiar with. Use object-oriented programming Method When designing a complex software system, the first problem is to determine which objects the system is composed of, and design Count these objects. In C++, each object is composed of two parts: data and function (ie operation code), as shown in the below Figure.

object-oriented programming

The data reflects the aforementioned “attributes”, such as a triangle object, its 3 side lengths are its attributes. function It is used to manipulate data in order to achieve certain functions, for example, the area of ​​a triangle can be calculated by the side length, And output the side length and area of ​​the triangle. Calculating the area of ​​a triangle and outputting related data is the aforementioned behavior. If you call a function in an object in the program, it is equivalent to sending a message to the object. Ask the object to achieve a certain behavior (function).


Encapsulation and Information in Object-Oriented Programming:

Concealment An object can be encapsulated, and some of its attributes and functions can be shielded from the outside world. The world is invisible, even unknowable. For example, there are circuit boards and mechanical control parts in the DVD player, but the outside is What you can’t see, from the outside, it is just a “black box” with several buttons on its surface. This is how the DVD player and the outside People don’t need to understand the structure and working principle of the DVD player.

The DVD player can perform the corresponding operations. The advantage of this is that it greatly reduces the complexity of people operating objects, and people who use objects do not need to Knowing the specific details inside the object, you only need to understand its external functions to operate the object freely. in daily life, The “point and shoot camera” is a typical example of the use of packaging principles. Users can have no idea about the working principle and internal structure of the camera As you know, you only need to know to press the shutter to take a picture. When designing an object, carefully consider how to seal it. Pretend to “conceal” the parts that are not necessary for the outside world to know. In other words, the internal implementation and external behavior of the object Separate. People control externally, and the specific operation details are implemented internally and are not transparent to the outside world. Clear. An important feature of the object-oriented programming method is “encapsulation”, the so-called “encapsulation”, Refers to two meanings: one is to encapsulate relevant data and operation codes in an object to form a basic unit, Each object is relatively independent and does not interfere with each other. The second is to hide some parts of the object from the outside, that is, to hide its internal details. In the festival, only a few interfaces are left in order to communicate with the outside world and receive messages from the outside world. This concealment from the outside world is called trust Information hiding (information hiding).

Information concealment is also conducive to data security, preventing unrelated people from understanding and modifying data. The function name (referring to the public function) in the C++ object is the external interface of the object, and the outside world can pass the function name To call these functions to achieve certain behaviors (functions). These will be described in detail later.


Abstract in Object-Oriented Programming:

In the programming method, the term abstraction (abstraction) is often used. In fact, the concept of “abstraction” is not Abstraction is very specific, and people are accustomed to it. For example, the term “person” we often use is an abstraction. Because there are only specific people in the world, such as Zhang San, Li Si, and Wang Wu. Put all people of Chinese nationality into one category, called “Chinese”, this is a kind of “abstraction”. Then abstract people from all countries including the Chinese, Americans, and Japanese as “people”. In real life, you can only see a concrete person, but not an abstract person. The abstract process Is to summarize the commonality of related things, The process of concentration. For example, all land vehicles that have wheels and can roll forward Called “car”. The gasoline engine-driven one is abstracted as a “car”, and the horse-drawn one is abstracted as a “horse cart”. “Integer” is an abstraction of all numbers without decimals such as 1, 2, 3, etc. The function of abstraction is to express the essence of the same kind of things. If you can use your own TV Even if you see a different brand of TV at home, you can definitely operate it, because it has all the TV sets. Shared characteristics.

The data type in C and C++ is an abstraction of a batch of concrete numbers. For example, “integer data” is Abstraction for all integers. Objects are concrete, such as a triangle can be used as an object, 10 triangles of different sizes are 10 Objects. These 10 triangle objects have the same properties and behaviors (but the specific side length values ​​are different), you can change them Abstraction is a type, called triangle type. In C++, this type can be defined as “class”. This Ten triangles are objects belonging to the same “class”. Just as 10 Chinese belong to the “Chinese” category, 10 Americans Belongs to the “American” category. A class is an abstraction of an object, and an object is a special case of a class, or a concrete manifestation of a class form.

Inheritance and Reuse in Object-Oriented Programming:

If a car manufacturer wants to produce a new type of car, it will generally not design it all from scratch.

Based on a certain model of car, some new functions are added to develop a new model of car. This is to improve health Common methods of productivity. If you have already established a “class” named A in software development, and you want to create another named B “Class”, while the latter is basically the same as the former, except that some attributes and behaviors are added on the basis of the former. Then design a new class from scratch, and only need to add some new content on the basis of class A. This is the object-oriented process Inheritance mechanism in order design. Using inheritance can simplify the steps of programming. For example: if everyone has Having fully understood the characteristics of horses, now I want to describe the characteristics of “white horses”. Obviously, it is not necessary to introduce what a horse is from the beginning, but just say Clearly, “a white horse is a white horse”. This simplifies people’s The knowledge and description of things simplifies work procedures. “White Horse” inherits the basic characteristics of “horse” and adds new characteristics (color). “Horse” is the parent category, or called the base The class “white horse” is derived from “horse” and is called a subclass or derived class. If you still want to define “white stallion”, just say Ming “a white stallion is a male white horse”. “White Stallion” is a subtype or derivative of “White Horse”.

 C++ provides an inheritance mechanism, and the inheritance method can easily use an existing class to create a new This can reuse part or even most of the existing software, which greatly saves programming workload. This is often The idea of ​​”software reusability” can not only use the classes you have built in the past, but also You can use the classes used by others or the classes stored in the class library, and these classes can be used after proper processing, which greatly shortens The software development cycle is of great significance to the development of large-scale software. 5. Polymorphism If there are several objects that are similar but not exactly the same, sometimes people require that when sending the same message to them, it They reacted differently and performed different operations. This situation is polymorphism. For example, A, B, C 3 The classes are all in the second grade. They have basically the same attributes and behaviors. When they hear the class bell at the same time, they will go separately Enter 3 classrooms without going to the same classroom. Similarly, if there are two armies, when you hear a kind of The sound of the trumpet, due to different prior agreements, the A army may carry out an offensive, while the B army may prepare to start a meal. Another example, in Windows

In the environment, double-click a file object with the mouse (this is to send a message to the object), if the object is An executable file, this program will be executed, if the object is a text file, a text editor will be launched and opened The document. There are many situations. In C++, the so-called polymorphism (polymorphism) refers to: related different classes produced by inheritance, which Objects will respond differently to the same message. Polymorphism is an important feature of object-oriented programming, which can increase the flexibility of the program.



The role of classes and objects in object-oriented programming

“Class” is a very important concept in C++, it is the basis of object-oriented programming. C++ to C The most important thing for improvement is to add a type of “class”. So C++ was originally called “C with classes”. class It is a common feature of all object-oriented languages, and all object-oriented languages ​​provide this type. If one Computer language does not contain classes, it cannot be called an object-oriented language. A C++ program of a certain scale is Composed of many categories. It can be said that classes are the soul of C++. If you don’t really master classes, you can’t really control them.

C++ supports process-oriented programming, as well as object-based and object-oriented programming. From this chapter to Chapter 4 introduces object-based programming. Including the concepts of classes and objects, the mechanisms and declarations of classes, and the definition of class objects And use etc. This is the basis of object-oriented programming. due to Object-based is based on class. Unlike process-oriented programs, object-based programs are based on classes and objects

Basically, the operation of the program is carried out around the object. On this basis, using inheritance and polymorphism, it becomes Object programming (sometimes not subdivided based on object programming and object-oriented programming, and the two are collectively referred to as Object-oriented programming). Object-based programming faces each object. All data belong to different objects. Face to The data in the process program is public or shared. If there are variables a, b, c, they can be used by different functions.

Call, which means that these data are lack of protection. The cross-use of data can easily lead to program errors. And real In fact, each set of data in the program is prepared for a certain operation, that is, a set of data is related to a set of operations. For the corresponding. Therefore, people imagine that related data and operations are put together to form a whole, which is relatively separated from the outside world. Separated. This is the object in object-oriented programming. In process-oriented structured programming, people often use this formula to express the program:

Program = Algorithm + Data Structure The algorithm and data structure are independent and designed separately, and the process-oriented programming is based on the algorithm. of. In practice, people gradually realize that algorithms and data structures are closely related to each other and inseparable. The method corresponds to a set of data structures, and it is not advisable to advocate that one algorithm corresponds to multiple sets of data structures, and one set of data structures corresponds to multiple data structures.

Algorithms. Object-based and object-oriented programming is to encapsulate an algorithm and a set of data structures in an object. Therefore, a new concept was formed:

Object = algorithm + data structure Program = (Object+Object+Object+…)+Message Or expressed as Program = Object S+ Message “Object” means “multiple objects”. The function of the message is to control the object. The key to programming is design Good for each object, and determine the commands issued to these objects, so that each object completes the corresponding operation.


Example write a program Using public and private in C++ Class

Output:

 

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: