473,890 Members | 1,642 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Forward reference compiler error...


Why does the following code cause a compiler error?
class A; // forward reference

class B
{
foo()
{
a = new A;

cout << a->bar(); // compiler error here
}

A* a;
}

class A
{
int bar()
{
return 1;
}
}
The compiler error I get is (note the use of 'struct' not 'class'):

error: invalid use of undefined type 'struct A'
error: forward declaration of 'struct A'
When I place the class B definition after class A, the error goes away. I
thought it was okay to use a "pointer" to an object of a forward-referenced
class.

Jun 27 '08 #1
6 1376
On 2008-05-03 10:03:33 -0400, "barcarolle r" <ba*********@mu sic.netsaid:
>
Why does the following code cause a compiler error?
class A; // forward reference

class B
{
foo()
{
a = new A;

cout << a->bar(); // compiler error here
}

A* a;
}

class A
{
int bar()
{
return 1;
}
}
The compiler error I get is (note the use of 'struct' not 'class'):

error: invalid use of undefined type 'struct A'
error: forward declaration of 'struct A'
When I place the class B definition after class A, the error goes away. I
thought it was okay to use a "pointer" to an object of a forward-referenced
class.
At the point of "new A" the compiler has to generate code to create an
object of tpye A. Since it hasn't seen the definition of A, it can't do
that.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jun 27 '08 #2

"Pete Becker" <pe**@versatile coding.comwrote in message
news:2008050310 124475249-pete@versatilec odingcom...
>
At the point of "new A" the compiler has to generate code to create an
object of tpye A. Since it hasn't seen the definition of A, it can't do
that.

Thank you for your response. Actually, it's not the new() that is causing
me problems. Let me present the problem in another way.
class A; // forward reference

class B
{
int print()
{

}

foo(A* a)
{
cout << a->print(); // compiler error here
}
}

class A
{
int print()
{

}

bar(B* b)
{
cout << b->print();
}
}

main()
{
a = new A;
b = new B;

b->foo(a);
a->bar(b);
}
Basically, I have two objects that are dependent on each other. I thought I
would be okay as long as I use pointers to these objects. Is there a way
around this problem (other than re-designing)?

Jun 27 '08 #3
On 2008-05-03 10:36:50 -0400, "barcarolle r" <ba*********@mu sic.netsaid:
>
"Pete Becker" <pe**@versatile coding.comwrote in message
news:2008050310 124475249-pete@versatilec odingcom...
>>
At the point of "new A" the compiler has to generate code to create an
object of tpye A. Since it hasn't seen the definition of A, it can't do
that.


Thank you for your response. Actually, it's not the new() that is causing
me problems. Let me present the problem in another way.
class A; // forward reference

class B
{
int print()
{

}

foo(A* a)
{
cout << a->print(); // compiler error here
}
}
At the point of the call to a->print() the compiler has to generate
code to call a member function of an object of type A. Since it hasn't
seen the definition of A, it can't do that.
>
Basically, I have two objects that are dependent on each other. I thought I
would be okay as long as I use pointers to these objects. Is there a way
around this problem (other than re-designing)?
Yup. Move the definition of B::foo outside the class definition, after
the definition of A.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Jun 27 '08 #4
In article <fv**********@a ioe.org>, ba*********@mus ic.net says...
Why does the following code cause a compiler error?
class A; // forward reference

class B
{
foo()
{
a = new A;

cout << a->bar(); // compiler error here
}

A* a;
}

class A
{
int bar()
{
return 1;
}
}
Because when you declare (but don't define) the class, it's an
incomplete type. You can create a pointer (or reference) to that type,
but anything that involves _dereferencing_ the pointer (among other
things) needs a _definition_ of the class.

For the compiler to handle something like 'a->b()', it has to have seen
declarations for both 'a' and 'b'. Using a reference would be the same
-- for you to use something like 'x.y()', it has to have seen
declarations of both 'x' and 'y'.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #5
barcaroller wrote:
>
When I place the class B definition after class A, the error goes away. I
thought it was okay to use a "pointer" to an object of a forward-referenced
class.
Use? No. It is OK to _declare/define_ a pointer to a forward-declared class. And
it is OK to _use_ that pointer in a number of very very limited ways. "Limited
ways" in this case means that it is not OK to apply a member access operators
('->' in your example) to this pointer, and it is not OK create object of that
forward-declared incomplete type using 'new'.

Move the definitions of the offending inline members to a point _after_ the
definition of class A, and the problem will go away.

--
Best regards,
Andrey Tarasevich
Jun 27 '08 #6
barcaroller wrote:
"Pete Becker" <pe**@versatile coding.comwrote in message
news:2008050310 124475249-pete@versatilec odingcom...
>>
At the point of "new A" the compiler has to generate code to create
an object of tpye A. Since it hasn't seen the definition of A, it
can't do that.


Thank you for your response. Actually, it's not the new() that is
causing me problems. Let me present the problem in another way.
class A; // forward reference

class B
{
int print()
{

}

foo(A* a)
{
cout << a->print(); // compiler error here
}
}

class A
{
int print()
{

}

bar(B* b)
{
cout << b->print();
}
}

main()
{
a = new A;
b = new B;

b->foo(a);
a->bar(b);
}
Basically, I have two objects that are dependent on each other. I
thought I would be okay as long as I use pointers to these objects. Is
there a way around this problem (other than re-designing)?
Ouput of program is
21

#include <iostream>

class A; // forward reference

class B
{
public:
int print()
{
return 1;
}

void foo(A* a);
};

class A
{
public:
int print()
{
return 2;
}

void bar(B* b)
{
std::cout << b->print();
}
};

void B::foo(A* a)
{
std::cout << a->print();
}

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

b->foo(a);
a->bar(b);

delete a;
delete b;
}


--
Jim Langston
ta*******@rocke tmail.com
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2059
by: Martin Eisenberg | last post by:
Hi! I have a header with two classes, WidthLogger and Hyst. WidthLogger is declared first; its ctor takes a Hyst reference. Hyst declares WidthLogger a friend. Hyst constructs a WidthLogger member, giving itself as parameter, and calls its log() method in various places. WidthLogger::log() then uses the reference to note down the values of some Hyst members. Except that I don't get that far because VC6 is bitchin', I hope
4
1673
by: exits funnel | last post by:
Hello, I have the following code: class A { public: A(int i = 0):asInt(i) { } operator B( ) { return B(asInt); } private:
11
2779
by: Randy Yates | last post by:
I'm having a problem with forward references. For example, class DATE; class MYCLASS; class MYCLASS { public:
3
20623
by: Michael Sgier | last post by:
Hello with the original code below I get the error: "forward declaration of `struct CPlayer'" class CPlayer; // what does this do? Instantiate the class CPlayer? // what's a forward declaration? class CEnemy : public CEntity { public:
23
3880
by: mark.moore | last post by:
I know this has been asked before, but I just can't find the answer in the sea of hits... How do you forward declare a class that is *not* paramaterized, but is based on a template class? Here's what I thought should work, but apparently doesn't: class Foo; void f1(Foo* p)
3
4111
by: DhaneshNair | last post by:
Hi all, I hav a file which is actually linkage file (used as an reference interface between c and c++ files). And this file has got two structures in it .. When i include this file directly i dont have any issues. but according to some norms in the review I am not supposed to use this file direclty in the header file .. but its fine if i use that inside the corresponding file. To avoid compiler error, i forward declared the structure...
10
1663
by: collection60 | last post by:
Will C++ ever have Java-like multiple level compiling? So that we can dump the old model of having to first declare then write the code? I find the declaration wastes so much time in coding. It's little more than something needed for the preprocessor, apart from that it is ancient junk. It's not needed in Java or other modern OOP languages (Visual Basic and REALbasic), so why C++?
4
5379
by: Steve | last post by:
Hi, I always though to return an instance of a class by value, it had to be defined - i.e. forward declaration isn't good enough? Consider the following code snippet: class RGBA; class Colour
3
2249
by: subramanian100in | last post by:
Consider the following piece of code stored in a file called x.cpp class Test; extern void fn_one(Test t); extern Test fn_two(); Test fn_three(const Test &obj) { fn_one(obj);
0
9977
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9816
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11218
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10910
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10452
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7161
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6036
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4260
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3268
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.