Identifier

The code.
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
#include <iostream>
using namespace std;

class Base
{
public:
	virtual bool foo(Base *) = 0;
};
class A : public Base
{
public:
	bool foo(Base *b)
	{
		B* b1 = dynamic_cast<B*>(b);
		return b1 == 0;
	}
};

class B : public Base
{
public:
	bool foo(Base *b)
	{
		A* a = dynamic_cast<A*>(b);
		return a == 0;
	}
};
int main()
{
	Base *aBase = new A();
	Base *bBase = new B();

	A *a = new A();
	B *b = new B();

	cout << boolalpha;
	cout << aBase->foo(bBase) << endl;
	cout << aBase->foo(a) << endl;
	cout << a->foo(bBase) << endl;
	cout << a->foo(b) << endl;

	system("pause");
}

errors
'B' : undeclared identifier: line 14
'b1': undeclared identifier: line 14
syntax error: identifier 'B': line 14
'b1': undeclared identifier: line 15

i think is because i use 'class B' before its definition..
In that respect, if i add a forward declaration to 'B' in line 3, i get
B*: invalid target for dynamic_cast
Well:
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
#include <iostream>
using namespace std;

class Base
{
public:
	virtual bool foo(Base *) = 0;
};
class A : public Base
{
public:
	bool foo(Base *b); // Note
};

class B : public Base
{
public:
	bool foo(Base *b)
	{
		A* a = dynamic_cast<A*>(b);
		return a == 0;
	}
};
	bool A::foo(Base *b) // Note
	{
		B* b1 = dynamic_cast<B*>(b);
		return b1 == 0;
	}
int main()
{
	Base *aBase = new A();
	Base *bBase = new B();

	A *a = new A();
	B *b = new B();

	cout << boolalpha;
	cout << aBase->foo(bBase) << endl;
	cout << aBase->foo(a) << endl;
	cout << a->foo(bBase) << endl;
	cout << a->foo(b) << endl;

	system("pause");
}
0h!!, how did i not think of that?

Thanks.
Topic archived. No new replies allowed.