Forward declarations of classes, invalid use

Hello,

I was given an assignment to write a program which demonstrates the usage of classes.

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
#include <cstddef> ///NULL

class BRANCH_CLASS;
class FRUIT_CLASS;

class BRANCH_CLASS
{
    unsigned int len;
    unsigned int fruits;
    FRUIT_CLASS ** fruit; ///That is supposed to be an array of pointers
    ///WOOD_CLASS * previous;
public:
    unsigned int getFruitsTotal(void)
    {
        return fruits;
    }
    unsigned int getLength(void)
    {
        return len;
    }
    /**WOOD_CLASS * getWoodPointer(void)
    {
        return previous;
    }**/
    unsigned int fd(void)
    {
        ///////////////////////////////
        (*(fruit + sizeof(FRUIT_CLASS))) ->fadeFruit();
    }
};
class FRUIT_CLASS
{
    unsigned int weight;
    BRANCH_CLASS * previous;
public:
    unsigned int getWeight(void)
    {
        return weight;
    }
    BRANCH_CLASS * getBranchPointer(void)
    {
        return previous;
    }
    void pluckFruit(void)
    {
        weight = 0;
        return;
    }
    void fadeFruit(void)
    {
        --weight;
        return;
    }
    void growthFruit(void)
    {
        ++weight;
        return;
    }
    unsigned int getLength(void)
    {
        return previous -> getLength();///
    }
};


A fruit needs to be aware of the branch on which it grows. Moreover, I am supposed to write a function for all branches that would decrease the weights of all produce on them. Because of that, I thought of using forward declarations for classes, yet the code refuses to work, specifically the fd function. I have no idea why. What causes the problem?
Last edited on
(*(fruit + sizeof(FRUIT_CLASS))) ->fadeFruit();

It's because you're trying to dereference a fruit before the compiler knows the full definition of the FRUIT_CLASS.

In your Branch class, just declare
unsigned int fd();

Then after the FRUIT_CLASS is defined, implement the fd function outside of the class definition itself:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class FRUIT_CLASS;

class BRANCH_CLASS {
    // ...
    unsigned int fd();
};

class FRUIT_CLASS {
    // ...
};

unsigned int BRANCH_CLASS::fd()
{
    // ...
}


Your other issue is that you aren't returning anything from your fd() function.

Third issue is that your dereferencing logic is wrong. Pointer arithmetic already takes into account the sizeof the class (which one reason why the full definition needs to be known).

Just use array syntax. It's the same thing.fruit[some_index]->fadeFruit();

PS: Having (void) to mean no parameters is not needed in C++. You can just do ().
Last edited on
Thank you very much! It worked.
Topic archived. No new replies allowed.