C++ Programming

object-oriented programming in C++ with examples

Description:

Object-oriented programming 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 its 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.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

What is object-oriented programming?

The idea of ​​object-oriented programming is similar to the idea of ​​dealing with problems in people’s daily life. In the natural 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 living room, bedroom, kitchen and bathroom; The colleges and schools are composed of many administrative departments and student classes. When people produce cars, they do not design and manufacture engines first, But they start with the entire designing from wheels to the chassis, after the design process then they start the manufacturing, perform different tests and when satisfied with everything the final step comes which involves the final manufacturing and assembly. 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.


Object

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. Similarly, a division, regiment, company, and squad in the army are all targets. The object is the basis of the system. 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 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 ending get out of class when you hear the bell, etc.), generally Call it “message”. Any object should have attributes (attribute)

With these two elements of behavior. Object should be able 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, and 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

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

For example, a person must press the buttons on the DVD player, or use the remote control DVD player to send an electrical signal to start the Player. Between objects This is how they communicate with each other by sending and receiving messages. Object-oriented programming 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 (i.e. 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

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 inside 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 know 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 the programming method, the term abstraction (abstraction) is often used. In fact, the concept of “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, Pakistanies, and Japanese as “people”. In real life, you can only see a concrete person, but not an abstract person. 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

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 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, 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

“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. My previous articles and this article 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. 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 is 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 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 operation. Therefore, people imagine that related data and operations are put together to form a whole, which is relatively separated from the outside world. 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. 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

#include <iostream>

using namespace std;

class home {

   private:

    double length;

    double breadth;

    double height;




   public:




    // function to initialize private variables

    void getData(double len, double brth, double hgt) {

        length = len;

        breadth = brth;

        height = hgt;

    }




    double calArea() {

        return length * breadth;

    }




    double calVolume() {

        return length * breadth * height;

    }

};




int main() {




    // create object of home1 class

    home home1;




    // pass the values of private variables as arguments

    home1.getData(42.5, 30.8, 19.2);




    cout << "Area of home =  " << home1.calArea() << endl;

    cout << "Volume of home1 =  " << home1.calVolume() << endl;




    return 0;

}

Output

Area of home =  1309

Volume of home =  25132.8

 

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button