Can you create pointers without initializing them?

Okay I'm reading a book that is talking about copying data from a previous class object into another class object. In this tutorial they're trying to teach me to use a pointer as the temporary object to copy the original class object. The only problem is, they never initialized the pointer... Can you do that? I thought that you always had to initialize and assign the pointer to a variable, but they never did that. Also, I don't get how they're able to copy the object data with another object because of the " Counter operator++()" function, can someone please give me some insight on that as well?


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
44
45
 // Listing 10.11
2:     // Returning the dereferenced this pointer
3:
4:     typedef unsigned short  USHORT;
5:     #include <iostream.h>
6:
7:     class Counter
8:     {
9:        public:
10:          Counter();
11:          ~Counter(){}
12:          USHORT GetItsVal()const { return itsVal; }
13:          void SetItsVal(USHORT x) {itsVal = x; }
14:          void Increment() { ++itsVal; }
15:          const Counter& operator++ ();
16:
17:       private:
18:          USHORT itsVal;
19:
20:    };
21:
22:    Counter::Counter():
23:    itsVal(0)
24:    {};
25:
26:    const Counter& Counter::operator++()
27:    {
28:       ++itsVal;
29:       return *this;
30:    }
31:
32:    int main()
33:    {
34:       Counter i;
35:       cout << "The value of i is " << i.GetItsVal() << endl;
36:       i.Increment();
37:       cout << "The value of i is " << i.GetItsVal() << endl;
38:       ++i;
39:       cout << "The value of i is " << i.GetItsVal() << endl;
40:       Counter a = ++i;
41:       cout << "The value of a: " << a.GetItsVal();
42:       cout << " and i: " << i.GetItsVal() << endl;
48:     return 0;
49: }
Indeed you can:

int* x; //points to random memory, probably not yours

As for the pre-increment operator, they are returning a const Counter&, based off *this. Then on line 40, they are copying it into a new Counter using the compiler provided copy ctor.
Topic archived. No new replies allowed.