Member of class A calling member of class B
May 16, 2011 at 11:39am UTC
Hello,
I know this may be a dumb question, I've searched in google and forums with no luck. Please help me get this code to work:
I want to call a member function of class B from a member of class A, and I can't seem to get the syntax right, the problem is at lines 10-11, the compiler error is:
cyclic_dep.cpp:11:7: error: request for member 'print' in 'b', which is of non-class type 'B*'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
class B;
class A
{
public :
void print () { cout << "\n A::print() " ; };
void printb(B * b) // <-
{ *b.print(); } // <-
;
};
class B
{
public :
void print () { cout << "\n B::print() " ; };
};
int main ()
{
A a;
B b;
a.print();
b.print();
cout << endl;
}
Andrei
May 16, 2011 at 11:44am UTC
I believe it is because in the forward declaration you do not declare the print() method (and you cannot declare it in forward declarations).
Since class B doesn't depend on class A, define class B before class A and forget about line 4 (the forward declaration).
May 16, 2011 at 11:49am UTC
The class B must be declared before class A otherwise anything of class B is unknown to class A
May 16, 2011 at 12:00pm UTC
Thank you all for your replyes,
this works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include <iostream>
using namespace std;
class B
{
public :
void print () { cout << "\n B::print() " ; };
};
class A
{
public :
void print () { cout << "\n A::print() " ; };
void printb(B * b)
{
cout << "\n A::printb() " ;
b->print() ;
}
;
};
int main ()
{
A a;
B b;
a.print();
b.print();
B * bp = &b;
a.printb( bp );
cout << endl;
}
Andrei
Topic archived. No new replies allowed.