Encapsulation, inheritance, and polymorphism of the three major features of C++

1 From C to C++

In the embedded software development process, most of them use C, a process-oriented language to develop. The C language is already very efficient in terms of efficiency. It is the best choice for embedded systems with tight hardware resources. However, with the improvement of hardware performance and the decline of hardware prices, C++ has gradually been used in embedded systems. When the compiler is optimized for C++ language, the code efficiency is close to that of C language, and it provides more advanced Language characteristics. (C language can also realize the characteristics of C++. The LINUX kernel uses a lot of object-oriented ideas)

2 Encapsulation

C language can also achieve encapsulation, using the struct keyword, putting functions into the structure is a fundamental change from C to C++ (C language uses function pointers). The ability to bundle data together with functions can be used to create new data types. This is called encapsulation. Encapsulation is for both data (attributes) and functions (behavior).

Encapsulation is an abstraction of the real world.

In fact, object-oriented programming can be summarized in one sentence, "send a message to an object". In fact, all things to do is to create a bunch of objects and send messages to them.

Why is encapsulation good?

  • Cohesion
  • Enhanced security and simplified programming
  • Code reuse

Hidden implementation:
In the C language, struct is the same as other data structures. There are no rules. The programmer can do whatever he wants in the struct, and there is no way to enforce any special behavior.
Three new keywords are introduced in the C++ language to set access boundaries in the structure, public, private, and protected.


  • All members declared public afterwards can be accessed by everyone.
  • Private
    except the creator of the type and the internal member functions of the class cannot be accessed by anyone.
  • Protected
    can access protected members in the inheritance structure, but not private members.

The class keyword is used in C++. It is the same in every aspect of struct in C language, except that the members of class are private by default, and the members of struct are public by default.

If a function is declared asfriendWhen, it means that it is not a member function of this class, but it can modify the private members of this class, and must be listed in the definition of this class. This is a privileged function, which breaks through the original access control authority.

3 Inheritance

C++ reuses code by creating new classes instead of creating them from scratch. Inheritance is a sublimation of abstraction. In the programming practice, the common features are extracted and placed in the parent class, and the class has characteristics that are different from other subclasses. (Is-a relationship)
Insert picture description here

Access permissions for subcategories:

Inheritance Public member of the base class Protected members of the base class Private members of the base class
public Still public Still protected not access
protected Become protected Still protected not access
private Become private Become private not access

Composition

Composition is another way of code reuse. Both composition and inheritance can put sub-objects in new types. Composition is usually used when you want a new class to have the functions of an existing class, instead of hoping to use an existing class as its interface, embed an object to implement the function of the new class, and users of the new class see the new definition Instead of the interface from the old class, embed the private object of the existing class inside the new class. (has-a relationship)

Insert picture description here
Inheritance and static members

  • All subclasses of static member variables have only one copy
  • Static member variables are initialized outside the class
  • Generally use static member functions to access static member variables
  • Static member functions have no this pointer and are not part of any object.

4 polymorphism

Polymorphism is achieved through virtual functions.
Polymorphism is dynamic binding at runtime.

Conditions for dynamic binding:

  • First: Only member functions designated as virtual functions can be dynamically bound
  • Second: The function call must be made through a reference or pointer of the base type

The reference or pointer of the base type can refer to the base type object or the derived type object.

The static type of the reference or pointer can be different from the dynamic type, which is the basis for C++ to support polymorphism. When calling a function defined in a base class through a base class reference or pointer, you cannot know the exact type of the function object to be executed. The object executing the function may be of the base class type or of a derived type.

class Base
{
public:
virtual void func(){}
};

class DevidedA :public Base
{
public:
virtual void func(){}
};
class DevidedB :public Base
{
public:
virtual void func(){}
};
/
Base *b = new DevidedB ();
b->func(); //调用 DevidedB::func();

4.1 Pure virtual function

The function is defined as a pure virtual function. This function provides an interface that can be overridden for descendant types, but it will not be called in this class. In addition, users cannot create objects of this class. This class is an abstract base class.

class Q_WIDGETS_EXPORT QAbstractButton : public QWidget
{
    Q_OBJECT
    ....
protected:
    virtual void paintEvent(QPaintEvent *e) = 0;
    ...
 };

void QRadioButton::paintEvent(QPaintEvent *)
{
    QStylePainter p(this);
    QStyleOptionButton opt;
    initStyleOption(&opt);
    p.drawControl(QStyle::CE_RadioButton, opt);
}

All the derived classes of QAbstractButton, QCheckBox, QPushButton, QRadioButton, and QToolButton, must implement the irretual void paintEvent(QPaintEvent *e) interface.

5 Overriding

  • Covered withRewriteIs a meaning
  • Covering is by means ofvirtualKeyword-implemented
  • Coverage isSubclass overrides the parent class
  • Subclass and parent class when overriddenFunction name, formal parameters, and return value are the same

FocusOutEvent taken from Qt source code

void QAbstractButton::focusOutEvent(QFocusEvent *e)
{
    Q_D(QAbstractButton);
    if (e->reason() != Qt::PopupFocusReason)
        d->down = false;
    QWidget::focusOutEvent(e);//显式调用
}

Specialized processing is done in the focusOutEvent method of QAbstractButton, and then focusOutEvent of the parent class is called for generalized processing.

6 Overload

Static polymorphism

6.1 Functions

Appear inIn the same scopeIf two functions (in the same class, in the same file) have the same name and have different formal parameter lists, they are regarded as overload functions of the function.translaterWhich function is called will be determined based on the type of the passed actual parameter. Functions cannot be based solely onDifferent return typesAnd to achieve overloading.

Examples of errors:

Record lookup(const Account&);
bool lookup(const Account&);
Record lookup(const Account&acct);
Record lookup(const Account&);
typedef Phone Telno;
Record lookup(const Phone&);
Record lookup(const Telno&);
Record lookup(Phone);
Record lookup(const Phone);

Correct example:

Record lookup(Phone&);
Record lookup(const Phone&);
Record lookup(Name);
Record lookup(Address);

6.2 Operator

Through operator overloading, the program can define different operator versions for the operands of the class type. Overloaded operators are functions with special names,Reserved word operatorFollowed by the operator symbols that need to be defined, like other functions, overloaded operators have return types and formal parameter lists.
format:

Object operator + (const Objcet&,const Object&);

Operators of built-in types cannot be overloaded (the "+" operator of type int cannot be overloaded)

If an overloaded unary operator is a member function, there is no formal parameter (explicit), if it is a non-member function, there is a formal parameter. Similarly, when a member defined by an overloaded binary operator has a formal parameter, it is defined as non- The member function has two formal parameters.

Operators are defined as non-member functions usually must be set to the operating classTomomoto(friend)

7 Redefining

whenThe subclass has the same name as the member of the base classTime willshieldDirect access to members of the base class.

7.1 Member variables

class Base
{
public:
	Base():mem(0){}
protected:
int mem;
};

class Derived :public Base
{
public:
	Derived():mem(0){} //初始化Derived::mem;
	int getMem()
	{
		return mem;//返回 Derived::mem;
	}
	int getBaseMem()
	{
		return Base::mem;//返回 Base::mem;
	}
protected:
int mem;
}

7.2 Member functions

Use in base class and subclassMember function of the same name, Its behavior is the same as the data: in the scope of the subclass, the members of the subclass will shield the members of the base class. Even if the function prototype is different, the base class members will be blocked.

class Base
{
public:
	Base();
	int func();
};

class Derived :public Base
{
public:
	Derived();
 	int func(int);
}

Base b;
Derived d;

b.func();
d.func(2);
d.Base::func();
d.func(); //error
  • Different scope
  • If you redefine an overloaded function in the base class, in the derived class, the name function in the base class (that is, all other overloaded versions) will be automatically hidden, including the virtual function of the same name
  • No requirement for function return value and formal parameter list

8 Useful references

"C++ Programming Thought"
"C++ Primer"
https://blog.csdn.net/lms1008611/article/details/81515727 (Picture)
https://www.cnblogs.com/DannyShi/p/4593735.html
https:// blog.csdn.net/haoel/article/details/1948051/

Guess you like

Origin blog.csdn.net/amwha/article/details/87520004