Friend class and NULL object member functions

K

KriS

Hi,

I have two simple questions:

1) Do I have to write storage-class-specifier, when I want to declare a
class as friend:

class Bar {};
class Foo { friend ??? Bar; };

VC++8 doesn't complain about it, g++ 3.4.4 throws an error and I can't
find anything about it in c++'98 standart.


2)
#include <iostream>

class Foo {
public: void print() { std::cout << "smth" << std::endl; }
};

int main() {
Foo* f = NULL;
f->print();
}

Works fine under g++ 3.4.4 and vc++8. As I understand this is undefined
behavior?
 
N

Noah Roberts

KriS said:
Hi,

I have two simple questions:

1) Do I have to write storage-class-specifier, when I want to declare a
class as friend:

class Bar {};
class Foo { friend ??? Bar; };

VC++8 doesn't complain about it, g++ 3.4.4 throws an error and I can't
find anything about it in c++'98 standart.

11.4.2 of 2003 states that a "elaborated-type-specifier" is required.
2)
#include <iostream>

class Foo {
public: void print() { std::cout << "smth" << std::endl; }
};

int main() {
Foo* f = NULL;
f->print();
}

Works fine under g++ 3.4.4 and vc++8. As I understand this is undefined
behavior?

That is correct.
 
A

andrew

Noah said:
That is correct.
More specifically, it only "works fine" because Foo::print() does not
reference any member variables. If it did, it would find that the
implicit this Foo* parameter would be NULL and cause a runtime memory
access error. Its probably better to make methods that do not use member
variables static to remove temptation.

Andrew
 
F

Fei Liu

KriS said:
Hi,

I have two simple questions:

1) Do I have to write storage-class-specifier, when I want to declare a
class as friend:

class Bar {};
class Foo { friend ??? Bar; };

VC++8 doesn't complain about it, g++ 3.4.4 throws an error and I can't
find anything about it in c++'98 standart.

you have to tell the compiler either it's a class or a method. In this
case, you clearly wanted to grant class Bar friend access. So use
'friend class Bar;'
 
N

Noah Roberts

andrew said:
More specifically, it only "works fine" because Foo::print() does not
reference any member variables.

"works fine" is one possible outcome of undefined behavior. Because
not referencing a member variable doesn't blow up here and now doesn't
mean it won't later or elsewhere. Undefined is undefined.
 

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,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top