Question

I'm getting an error below in the class a declaring a new pointer of type b. Please help.

#include <iostream>

namespace B
{
    class b;
}
class a
{
    private:

    B::b* obj_b;

    public:

    a(){}
    ~a(){}
    void create()
    {
        b* obj_b = new b;
    }
};
class b
{
    private:

        a *obj_a;

    public:
        b()
        {
            obj_a->create();
        }
        ~b(){}
};
int main()
{
    b obj;

    return 0;
}
Was it helpful?

Solution

There were many errors in your code. These are related to forward declaration, fully qualified name usage etc.

namespace B 
{ 
   class b; 
} 
class a 
{ 
private: 

   B::b* obj_b;            // change 1 (fully qualified name)

public: 
   void create();          // change 2 (can't use b's constructor now as B::b is not 
                           // yet defined)
   a(){} 
   ~a(){} 

}; 

class B::b                 // change 3 (fully qualified name)
{ 
private: 

   a *obj_a; 

public: 
   b() 
   { 
      obj_a->create(); 
   } 
   ~b(){} 
}; 

void a::create()             // definition of B::b's constructor visible now.    
{ 
   B::b* obj_b = new B::b;   // And here also use fully qualified name
} 

int main() 
{ 
   B::b obj; 

   return 0; 
} 

OTHER TIPS

b* obj_b = new b;

And there is your problem. You can declare a pointer to a B because pointers are all the same size, but you cannot construct one or take one by value without providing the class definition to the compiler. How would it possible know how to allocate memory for an unknown type?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top