compile problem: friend class w/ non default constructor

A

ankit_jain_gzb

Hi
Iam not able to understand why the following code gives compile
problem.
Thanks
Ankit Jain

class B;

class A{
public:
friend class B;
B* x;

A()
{
x = new B(3)
}
};

class B{
public:

B(int i)
{
}
};

int main()
{
return 0;
}

error coming in vc++ (6.0) is --> error C2514: 'B' : class has no
constructors
 
J

John Carson

ankit_jain_gzb said:
Hi
Iam not able to understand why the following code gives compile
problem.
Thanks
Ankit Jain

class B;

class A{
public:
friend class B;
B* x;

A()
{
x = new B(3)
}
};


The problem is that at the point at which you define the A constructor, the
B constructor has not yet been declared.
class B{
public:

B(int i)
{
}
};

int main()
{
return 0;
}

error coming in vc++ (6.0) is --> error C2514: 'B' : class has no
constructors


Try doing it in this order:

class B;

class A{
public:
friend class B;
B* x;
A();
};

class B{
public:
B(int i)
{}
};

// Now the B constructor has been declared,
// we can use it in the A constructor. I declare
// it inline because functions defined in the
// class declaration, as per your version,
// are implicitly inline.

inline A::A()
{
x = new B(3);
}


int main()
{
return 0;
}
 
L

Larry I Smith

ankit_jain_gzb said:
Hi
Iam not able to understand why the following code gives compile
problem.
Thanks
Ankit Jain

class B;

class A{
public:
friend class B;
B* x;

A()
{
x = new B(3)
}
};

class B{
public:

B(int i)
{
}
};

int main()
{
return 0;
}

error coming in vc++ (6.0) is --> error C2514: 'B' : class has no
constructors

Move the class B def so it preceeds the class A def.
'A' is trying to invoke 'B(int)' which has not yet been
defined at that point in the source file.

Larry
 
J

Jerry Coffin

[ ... ]
class B;

class A{
public:
friend class B;
B* x;

A()
{
x = new B(3)
}

Try moving the definition of B before A, as in:

class B{
public:

B(int i) {}
};

class A{
public:
friend class B;
B* x;

A() {
x = new B(3);
}
};

While you're at it, initialization is generally preferred to
assignment, giving:

A() : x(new B(3)) {}

Since all of A is public, declaring B as its friend isn't
accomplishing anything (though I suspect this was added in an attempt
at getting A to see B's ctor).
 
A

ankit_jain_gzb

Thank you : John.

Taking the function(constructor here) declaration outside the class
really worked.

Thanks to others too but I could not move the definition of B above A
because B(the class below A) has reference to A. Sorry I did not show
in prototype code.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top