forward decl

I want to write a simple program to demonstrate a factory method but it failed to compile. I couldn't figure out why didn't it compile...
here is the compile error:
test.cpp: In member function ‘A* A::create(int, int)’:
test.cpp:10: error: invalid use of incomplete type ‘struct B’
test.cpp:3: error: forward declaration of ‘struct B’

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
#include<iostream>
using namespace std;
class B;
class C;
class A
{
	public:
		A* create(int a,int b)
		{
                    if (b==1)
                    {  
			B* bo = new B;
                        return bo;
                    }
                    else
                    { 
                        C* co = new C;
                        return co;
                    }
		}
		void setVal(int n)
		{
			_a = n;
		}
	protected:
		int _a,_b;
	private:
};

class B : public A
{
	public:
	protected:
	private:
};

class C : public A
{
	public:
	protected:
	private:
};

int main()
{

}
Last edited on
It appears that c++ doesn't like you using undefined classes.
You could probably solve this by taking function definition outside class A{ }
that is:
1
2
3
4
5
6
7
8
9
10
11
class A{
    A* create(int a, int b);
   //and other declarations
};
class B{/*...*/};

class C{/*...*/};

A* A::create(int a, int b){
    //define here
}
Last edited on
yes, that's right.
i couldn't thought that.
thank you.
From a design perspective, however, super-classes should not know about its sub-classes.

Topic archived. No new replies allowed.