Sign in to follow this  

Forward declarations and return values

Recommended Posts

GCC is letting me do something I didn't think was allowed and I was just wondering if this is non-standard or undefined behaviour or not?

I have a Om::Value class, and an Om::ValueList class. ValueList needs to include OmValue.h as it has, for example, Value operator[](int index) method.

But I'm trying to add a ValueList toList() method to Value, which means I have a circular dependancy. But I noticed that if I forward declare ValueList at the top of OmValue.h, GCC is then allowing me to use ValueList as a return type (not a reference or pointer):

class ValueList;

class Value
{
public:
    // snip

    ValueList toList() const; // thought this would throw a "not defined" error?
};
I thought this was not allowed since the compiler would need to know the size of ValueList? Is this non-standard or undefined or something GCC is allowing through an extension, or is this perfectly valid standard C++?

Share this post


Link to post
Share on other sites

It doesn't need to know the size until toList() is actually called. So the declaration is legal, but using the function without the full class definition will give an undefined error.

Share this post


Link to post
Share on other sites
Posted (edited)
I thought this was not allowed since the compiler would need to know the size of ValueList?

Where does it need that size here?

"ValueList toList() const" says "There is a 'toList' method in the class, it outputs an object of type ValueList". The class definition only needs the size of the (reference to) the 'toList' method. That reference is not changing size depending on the size of the result of the call. The class definition also does not store the result due to this line.

 

In context of an actual call to Value::toList(), the code needs to know the size to create space for the return value. It also needs to know the size in context of the 'toList' method implementation, ie

class Value
{
    ...
    ValueList toList() const
    {
        ...
        return values;
    }
};

but you don't do that either here.

Edited by Alberth

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this