friend function: member function of another class giving error if defined before

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

using namespace std;

class test;

class sampletest
{
        public:
                void getainb(test & x);
               
};

void sampletest::getainb(test & x)
                {
                        cout<<"In sampletest:getainb="<<x.a<<endl;
                }

class test
{
        int a;
        public:
        int geta() {return a;}
        void seta(int x) { a = x;}
        friend void sampletest::getainb(test & x);
};


main()
{
        test t;
        t.seta(23);


                sampletest s;
                s.getainb(t);

}

giving error:
class.cpp: In method `void sampletest::getainb(test &)':
class.cpp:14: invalid use of undefined type `class test'
class.cpp:6: forward declaration of `class test'


But if i move defination of getainb after class test
it works fine.


trying to understand why its giving error.




working code below.
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
class test;


class sampletest
{
        public:
                void getainb(test & x);
        
};


class test
{
        int a;
        public:
        int geta() {return a;}
        void seta(int x) { a = x;}
        friend void sampletest::getainb(test & x);
};

void sampletest::getainb(test & x)
{
        cout<<"In sampletest:getainb="<<x.a<<endl;
}

main()
{
        test t;
        t.seta(23);


                sampletest s;
                s.getainb(t);

}




Is it because to acess members compiler needs defination information prior, forward declaration should it not work for this,

Request for your inputs to clear my doubt
Last edited on
I think it's because the compiler needs to know more about class test than just the forward reference.
Topic archived. No new replies allowed.