C++ is one of the most widely used programming languages in the world. It is very flexible as one can work both at high-level abstraction and low-level hardware features. Here we will briefly talk about Pointer, Reference, Virtual Methods, and Struct. I will also try to keep this post updating :).
1. Pointer and Reference
In C++, objects (variables, classes, …) are ALL value type except using an explicit reference (T&) or a pointer (T*). As value types are copyable, when assigning an instance of a class to another instance, the assignment is done member-wisely. For example:
1 | class A{ |
If one wants a reference type of object, one can take use of reference (T&) or a pointer (T*). Reference and pointer both store the address of a variable which is located elsewhere in the memory. The difference between them is that reference can be seen as an alias of an existing variable, and it cannot be changed to refer to another object or null after it is initialized. In short, reference is like a constant pointer.
Additionally, a pointer itself has its own memory address and size on the stack, while a reference shares the same memory address with the variable it refers to (but it still takes up some space on the stack).
1 | int i = 3; |
2. Virtual Methods, Virtual Table and Virtual Pointer
When virtual method is defined by a class or a base class, the compiler will create a virtual pointer and virtual table for the class. Virtual pointer is usually located at the first place in the object memory, and points to the virtual table (the first virtual method in the virtual table).
The virtual table saves all the addresses of the virtual methods with the same order as they are defined. When inheriting, virtual methods of the derived class are placed in the virtual table of the first base class. It means that the virtual table should have the addresses of the virtual methods in the base class itself (if the derived class overrides, then only save the overrided methods from the derived class) and the new virtual methods in the derived class.
1 | class Base |
3. Struct and Class
There are very small differences between structs and classes in C++. The only difference is that members in structs are by default public while members in classes are by default private. But both structs and classes can have private, public, or protected members.
When inheriting, structs are public inheritance by default and classes default to private inheritance.