Question

I have tried to use a constructor as a default value in a method declaration, like this:

A.hpp

#include "B.hpp"
class B;
Class A {
friend class B;
    public:
    A();
    ~A();
    const A& operator = (const A& rhs) {
        // assignment operations
        return *this;
    }
    int do_something (B* pB);
};

B.hpp

#include "A.hpp"
class B {
    public:
    B(const A a = A());
    ~B();
};

My gcc 4.8 C++11 compiler is not happy with the line B(const A a = A());:

error: 'A' does not name a type error: ISO C++ forbids declaration of 'A' with no type [-fpermissive]

I need a default value for a, and I don't want to use a pointer like in B(A *a = NULL, int z = 0);.

I have also tried to declare a static element and use this object as the default value:

A.hpp

#include "B.hpp"
class B;
class A {
    // ...
};

B.hpp

#include "A.hpp"
A a0;
class B {
    public:
    B(const A a = a0);
    ~B();
};

I get exactly the same errors.

How can I achieve that please ?

EDIT: make the code closer to the real code.

Was it helpful?

Solution 4

I finally found the origin of the problem, it was due to a bad use of #include.

Removing the line #include "B.hpp" in A.hpp solves the problem. The A header only needs a forward declaration of class B, since it uses only a pointer to this class. I conclude I had a circular header reference. I thought that using friend requires to include the header of the class. Note: class B needs to access actually some private members of class A.

Sorry for my bad initial post, it was impossible to diagnose anything from it since it was not close enough from the real one (coorected). I will stick to SSCCE next time. Thanks everyone. As the buddy concludes here, "That was really stupid". Then I found detailed explanations here and here.

OTHER TIPS

You have to add semicolons after the closing brace of your classes.

class A        class A
{              {

} /* bad */    }; /* good */

Move the static variable declaration a0 to AFTER the definition of class A, like so:

class A
{
    // class definition
};

A a0;

class B
{
    B (const A a = a0);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top