C++ Miscellaneous

C++ is really complex, though interesting. There are many details and I think it's not possible to remember all. This post is to record any useful information I find about C++, and will be kept updating. If there are topics needed to further explanation, I may write a new post specific for that.

C++ pointer and reference

1
2
3
4
5
6
7
8
int i = 1;

// create a pointer
int* pint = &i;

// create a reference
int& rint = i;

Pointers and References are treated in the same way by the compiler

https://stackoverflow.com/questions/11347111/dereferencing-a-pointer-when-passing-by-reference

If created a reference to a variable (not a pointer), then the address that the reference points to can't be modified, which is not like a pointer.

C++ Cast

c++ - Regular cast vs. static_cast vs. dynamic_cast - Stack Overflow

Dynamic cast: cast from base class to derived class, but there must be at least one virtual method in the base class. If trying to cast for incompatible classes, it fails and returns a null pointer.

Static cast: do not check the compatibility of classes cast (? not sure, but the following code will run, which cast CB object into CC object). But will check things like casting an int pointer to a char pointer, to avoid memory error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class IA {
public:
void mp_Print() {
std::cout << "IA" << std::endl;
}
};

class CB : public IA {
public:
void mp_Print() {
std::cout << "CB" << std::endl;
}
};

class CC : public IA {
public:
void mp_Print() {
std::cout << "CC" << std::endl;
}
};

void gp_SomeFunction(IA* arg) {
arg->mp_Print();
CB* lv_pCast2CB = static_cast<CB*>(arg);
if (lv_pCast2CB) {
lv_pCast2CB->mp_Print();
}
else {
std::cout << "null pointer" << std::endl;
}

}

int main()
{
CB lv_cb;
gp_SomeFunction(&lv_cb);

CC lv_cc;
gp_SomeFunction(&lv_cc);

std::cout << "Hello World!\n";
}

Explicit constructor

Use of explicit keyword in C++ - GeeksforGeeks To prevent implicit type conversion for the constructor that can be called with only one argument

C++ Standard Terms

For this I think might be better to read some books consistent with C++ standard terms.

It is the first time I know that C++ has defined some terms for OO concepts: object, subobject, base class, derived class. Understandable but not the same as usally used in OO programming such as superclass, parent, child, ....

https://stackoverflow.com/questions/18451683/c-disambiguation-subobject-and-subclass-object