thundium
thundium

Reputation: 1063

Why define Parent class as friend class?

I am looking at other's code and find one part I can't understand.

class a {
   public:
   function xxx () {.....}
}

class b : public a {
   public:
       xxxx
   protected:
       constructor()....

       friend class a ;            <=  here why it is needed ????

}

As I understand, since b had already inherited from a, it should be able to use the function of a directly. What's the purpose of this "friend" declaration used for?

Upvotes: 0

Views: 85

Answers (5)

Pete Becker
Pete Becker

Reputation: 76458

It almost certainly means that there is a serious design problem. One of the basic rules of thumb for inheritance is that base classes should not need any information about derived classes. Making a a friend of b makes it possible for member functions of a to get at the internals of b objects.

Upvotes: 0

Lovely Pufferfish
Lovely Pufferfish

Reputation: 7

Depending on your projects/requirements, your class designs change. I have no comment on your class hierarchy but true your question is all about theories of friend usage. If you don't use friend, you will not be able to call B members from A. It is there for...cross-mating :D

Upvotes: 0

utnapistim
utnapistim

Reputation: 27385

As I understand, since b had already inherited from a, it should be able to use the function of a directly.

Yes. The friend specification though allows access the other way around (instances of a will be able to access private data and functions of b).

What's the purpose of this "friend" declaration used for?

The example above doesn't suggest any. The only situation where it may make sense is with using CRTP in certain situations (i.e. a is a template of b) but even so, if you see such a requirement ("must add friend declaration in b") it is possible that the design you're looking at is flawed.

Can you post a concrete example?

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227538

friend class a; grants class a the right to access non-public members of b. So in this small example, an instance of a can call b::constructor(). Without friendship, it wouldn't be possible.

As to why, there is not enough information to answer that, other than there must be a need for instances of a to call b::constructor() (assuming that to be anything other than the syntax error it currently is).

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258638

The friend allows a to use b's methods, not the other way around, which isn't implicit.

The design looks fishy though, a base class shouldn't care about derived classes.

Upvotes: 1

Related Questions