File: personconstr.cc

package info (click to toggle)
c%2B%2B-annotations 11.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 11,244 kB
  • sloc: cpp: 21,698; makefile: 1,505; ansic: 165; sh: 121; perl: 90
file content (73 lines) | stat: -rw-r--r-- 2,012 bytes parent folder | download | duplicates (10)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    COMMENT(
Also note that
the example doesn't show where the destructor is called; this action occurs
implicitly when the below function tt(main()) terminates and hence when its
local variable tt(p) ceases to exist.



    When tt(printperson()) receives a fully defined tt(Person) object (i.e.,
containing a name, address and phone number), the data are correctly printed.
However, when a tt(Person) object is only partially filled, e.g. with only a
name, tt(printperson()) passes 0-pointers to tt(cout). This unesthetic
feature can be remedied with a little more code:

verb(
    void printperson(Person const &p)
    {
        if (p.name())
            cout << "Name   : " << p.name() << "\n";
        if (p.address())
            cout << "Address : " << p.address() << "\n";
        if (p.phone())
            cout << "Phone  : " << p.phone() << "\n";
    }
)
Alternatively, the constructor tt(Person::Person()) might initialize the
members to `printable defaults', like tt(" ** undefined ** ").



    The destructor, constructor and the class definition are given below.

verb(
    // class definition
    class Person
    {
        public:
            Person();          // constructor
            ~Person();         // destructor

            // functions to set fields
            void setName(string const &n);
            void setAddress(string const &a);
            void setPhone(string const &p);

            // functions to inspect fields
            string const &name() const;
            string const &address() const;
            string const &phone() const;

        private:
            char *name;             // name of person
            char *address;          // address field
            char *phone;            // telephone number
    };

    // constructor
    Person::Person()
    {
        name = 0;
        address = 0;
        phone = 0;
    }

    // destructor
    Person::~Person()
    {
        free(name);
        free(address);
        free(phone);
    }
)
END COMMENT)