I am learning C++ using the book "C++ Primer", and write some small code to test the concepts I am learning.
According to the book, a friend a class can be:
(1) a non-member function
(2) a member function of another class
(3) another class
I am testing how to write a friend of class A , which is a member function of class B. Below is my code:
Code:
class A;
class B{
public:
int getValue(A* pa) {
return pa->va_;
}
};
class A {
friend int B::getValue(A* pa);
public:
A():va_(1){}
private:
int va_;
};
I always got the error of: error C2027: use of undefined type 'A'
I used forward declaration of class A, and pointer to A in class B, why this does not work?
That doesn't matter. By trying to return the 'va_' member variable, the compiler needs to know the declaration of the class. Try it this way:
Code:
class A;
class B{
public:
int getValue(A* pa);
};
class A {
friend int B::getValue(A* pa);
public:
A():va_(1){}
private:
int va_;
};
inline int B::getValue(A* pa) {
return pa->va_;
}
Got it! The key point here is whether I de-reference the pointer.
Another question. The reason I use pointer here is forward declaration. From what I learned, generally forward declaration works only with pointer or reference to the class.
I tried to replace A* with A&, the code is still ok and this is understandable. However, If I use pass by value, I was surprised to see the code still works.
Code:
class A;
class B{
public:
int getValue(A pa);
};
class A {
friend int B::getValue(A pa);
public:
A():va_(1){}
private:
int va_;
};
inline int B::getValue(A pa) {
return pa.va_;
}
So, since the inline getValue(A pa) is defined at the end (after definition of class A), it does not matter we use point, reference, or pass by value, with respect of forward declaration, right?
Last edited by featips; April 20th, 2010 at 05:52 PM.
Actually, it's just a quirk of the language: function parameters are always allowed to be forward-declared, no matter how they're passed.
The reason is that you only need the actual definition when you need either (a) the size of the object or (b) some member of the object. Since function parameters are pushed onto the stack at runtime rather than compile time, neither of those is necessary in order to declare function parameters.
Cool, 'function parameters are pushed onto the stack at runtime rather than compile time'...great, this is a wonderful forum!
Originally Posted by Lindley
Actually, it's just a quirk of the language: function parameters are always allowed to be forward-declared, no matter how they're passed.
The reason is that you only need the actual definition when you need either (a) the size of the object or (b) some member of the object. Since function parameters are pushed onto the stack at runtime rather than compile time, neither of those is necessary in order to declare function parameters.
Bookmarks