C++ help

Started by
11 comments, last by _nomad_ 19 years, 8 months ago
here is a code:

class B;

class A {
B* b;
public:
  A() { b = new B(this); }
};

class B {
A a;
public:
  B(A a) { a = a; }
};
when i compile with msvc++ 6, the compiler says there is no constructor for class B? help.
Advertisement
this is a pointer, you must dereference the this pointer to use your other constructor. Also, a = a [probably] won't work as you expected. Change the parameter name or explicitly qualify like this->a = a;
hi,

i changed the code using the previous reply's comment to:

class B;class A {B* b;public:  A() { b = new B(this); }};class B {A* a;public:  B(A* pa) { this->a = pa; }};



i still get the same error, which is:
"error C2514: 'B' : class has no constructors"


help.
You need to swap the definitions of class A and B, forward declaring A.

class A;class B {A* a;public:  B(A* pa) { this->a = pa; }};class A {B* b;public:  A() { b = new B(this); }};<br><br></pre></div><!–ENDSCRIPT–> 
thanks! but the problem is that i need to make an instance of class B inside class A (which was my code in my first post was trying to do).

any ideas would be great. thanks!!!
You can have an instance of one in the other for one of the classes but not the other.

class A;

class B
{
A* a;
public:
B(A* ap) { a = ap; }
};

class A
{
B b;
public:
A(B bp) { b = bp; }
};

yes, thanks. but the problem is that i need to instantiate class B inside class A... if this is not possible, thanks anyway. =)


With an A* to the enclosing class you mean?

class A;

class B
{
A* a;
public:
B(A* ap) { a = ap; }
};

class A
{
B b;
public:
A() : b(this) { }
};

// usage
A a;
B b(&a);

hi, here's what i'm trying to do:



class A;class B {A* a;public:B() { a = new A(1);          a->print();   }};class A {int temp;public:A(int n) { temp = n; }void print() { printf(%d, &temp); }};// usageB*b;b = new B();//should print 1 to console




the code above gets the error:
error C2514: 'A' : class has no constructors


i need class A even though class B is there first.
The C++ compiler works top to bottom. When it gets to B, it sees it needs to know all about A, but it hasn't found the definition of A yet. Hence, error.

Because A makes no mention of B, there is no reason to define B before A. Put the class definition of A before B, and the constructor will have been defined, and your code will work.

This topic is closed to new replies.

Advertisement