A Preliminary Study on the Object-Oriented Model of C++

The C++ object model can be summarized into the following two parts:
1> The part of the language that directly supports object-oriented programming, such as constructors, destructors, virtual functions, inheritance, polymorphism, etc.
2> For various supported underlying implementation mechanisms

Basic knowledge:
C++ class starts from object-oriented theory, defines variables (attributes) and functions (methods) together, and is used to describe the real world.
the type. From the computer's point of view, programs are still composed of data and code segments.
How does the C++ compiler complete the conversion of object-oriented to computer programs?
In other words, how the C++ compiler manages the relationship between classes, objects, classes and objects.
Specifically: a specific object calls a method in a class, then how does the C++ compiler distinguish that specific object and call this method

Internal Handling of Common Member Functions by C++ Compilers
1> Member variables and member functions in C++ class objects are stored separately.
Ordinary member variable: stored in the object, has the same memory layout and byte alignment as struct variables. // stack area
Static member variables: stored in the global data area.
Ordinary member function: stored in the code segment.

So here comes the question: Many objects share a piece of code? How does the code distinguish between concrete objects?

Source code: Pay attention to understanding
/*
	How does the C++ compiler manage static and non-static members?
*/


# include <iostream>


using namespace std;


class Text
{
private:
	int m1;
public:
	Text(int i)
	{
		m1 = i;
	}
	int getI ()
	{
		return m1;
	}
	static void printI ()
	{
		cout << "This is calss text" << endl;
	}


};
Text a(10);
a.getI();
Text :: printI ();



 Translate to C language
struct Text
{
	int m1;
};
void Text_initialize(Text * pThis, int i)
{
	pThis->m1 = i;
}
int Text_getI(Text * pThis)
{
	return pThis->m1;
}
void Text_printI ()
{
	printf("This is class Text\n");
}
Text a;
Text_initialize(&a, 10);
Text_getI(&a);
Text_printI ();			

Summarize:
1> Member variables and member functions in C++ class objects are stored separately, and the four memory areas in C language are still valid
2> Ordinary member functions of classes in C++ implicitly contain a this pointer to the current object.
3> Static member functions and member variables belong to classes.
The difference between static member function and ordinary member function:
A static member function does not contain a pointer to a concrete object

Ordinary member functions contain a pointer to a concrete object

------------------------------------------------------------------------------------------------------

Content reference: Chuanzhi podcast video (video is super suitable for self-study C++ basic video)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325563017&siteId=291194637