How can I make these classes live in peace and cooperate with eachother?

When I have e forward declaration of PoliceOfficer the compiler complains invalid use of incomplete type 'struct PoliceOfficer'

But when I take away the forward declaration it complains that 'PoliceOfficer' has not been declared

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



#include <iostream>

using namespace std;


class PoliceOfficer;


class ParkingTicket
{
    public:

        string getOfficerName(PoliceOfficer &theOfficer)
        {
            return theOfficer.officerName;
        }

        int getOfficerBadgeNumber(PoliceOfficer &theOfficer)
        {
            return theOfficer.officerBadgeNumber;
        }

};


class PoliceOfficer
{
     friend class ParkingTicket;


    private:

        string officerName;
        int officerBadgeNumber;
        ParkingTicket* theTicket;


    public:
        void giveTicket()
        {
            theTicket = new ParkingTicket;
        }


};
         

int main()
{

    return 0;
}
Last edited on
Use forward declaration of PoliceOfficer but do not define the functions that use this class until after the PoliceOfficer class has been defined.
Last edited on
Well, if I reverse the order of the classes like this and also forward declare parking ticket then I get

1
2
3
error: invalid use of incomplete type ‘struct ParkingTicket’|
error: forward declaration of ‘struct ParkingTicket’|
error: multiple types in one declaration|


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
#include <iostream>

using namespace std;


class PoliceOfficer;
class ParkingTicket

class PoliceOfficer
{
     friend class ParkingTicket;


    private:

        string officerName;
        int officerBadgeNumber;
        ParkingTicket* theTicket;


    public:
        void giveTicket()
        {
            theTicket = new ParkingTicket;
        }


};

class ParkingTicket
{
    public:

        string getOfficerName(PoliceOfficer &theOfficer)
        {
            return theOfficer.officerName;
        }

        int getOfficerBadgeNumber(PoliceOfficer &theOfficer)
        {
            return theOfficer.officerBadgeNumber;
        }

};


int main()
{

    return 0;
}
You can define the functions outside the class definitions.
Topic archived. No new replies allowed.