1Every object in C++ has access to its own address through an important pointer called this pointer.
2 The this pointer is an implicit parameter to all member functions.
3Therefore, inside a member function,
4 this may be used to refer to the invoking object.
5
6Friend functions do not have a this pointer,
7 because friends are not members of a class.
8Only member functions have a this pointer.
1#include <iostream>
2using std::cout;
3
4int main() {
5 /*
6 Some things to keep in mind:
7 -you shouldn't circumvent the type system if you are creating raw ptrs
8 and don't need to "type pun" or cast (don't use void ptrs)
9 -ptr types only reference memory (which are integers), not actual data, thus
10 they should not be treated as data types
11 char* is just 1 byte of mem, int* is just 4 bytes of mem, etc
12 - '*' means that you are creating a pointer which "points" to the mem address
13 of a variable
14 - '&', in this case, means "get the mem address of this variable"
15 */
16
17 void* ptr; // a pointer that doesn't reference a certain size of memory
18 int* int_ptr; // a pointer that points to data with
19 // only 4 bytes of memory (on stack)
20
21 int a = 5; // allocates 4 bytes of mem and stores "5" there (as a primitive)
22 ptr = &a; // can only access the memory address of 'a' (not the data there)
23
24 int b = 45;
25 int_ptr = &b; // can access both memory address and data of 'b'
26
27 cout << ptr << "\n"; // prints mem address of 'a'
28 /*cout << *ptr << "\n"; <- this will error out; a void ptr cannot be
29 derefrenced */
30 cout << *(int*)ptr << "\n"; // type punning to get around void ptr (extra work)
31
32 cout << int_ptr << "\n"; // mem address of b
33 cout << *int_ptr << "\n"; // data stored at b
34
35 /* -- OUTPUTS -- */
36 /*
37 some memory address (arbitrary) which contains 05 00 00 00 as its data
38 5
39 some memory address (arbitrary) which contains 2D 00 00 00 as its data
40 45
41 */
42
43 return 0; // you only need this if "main" isnt the linker entry point
44 // you also don't care
45
46 // ur also probably wondering why I didn't using namespace std... cherno
47}
1#include <iostream>
2using namespace std;
3class Demo {
4private:
5 int num;
6 char ch;
7public:
8 void setMyValues(int num, char ch){
9 this->num =num;
10 this->ch=ch;
11 }
12 void displayMyValues(){
13 cout<<num<<endl;
14 cout<<ch;
15 }
16};
17int main(){
18 Demo obj;
19 obj.setMyValues(100, 'A');
20 obj.displayMyValues();
21 return 0;
22}