pandoragami
pandoragami

Reputation: 5585

forward declaration and typename using new keyword

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;
}

Upvotes: 1

Views: 1050

Answers (2)

Chubsdad
Chubsdad

Reputation: 25507

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; 
} 

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124672

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?

Upvotes: 6

Related Questions