Just because someone trusts you does not automatically mean they will trust
your children.
Suppose class Fred grants friendship privileges to another class Base and
class Derived is derived from class Base. Derived does not automatically
have friendship privileges to access the innards of Fred just because its
base class is a friend of Fred. This rule improves encapsulation. Without
this rule, anyone could automatically gain friendship (and access to
internals) by deriving from a known friend.
class Base;
class Fred {
friend Base;
};
class Base {
//Member functions of Base are friends of Fred
};
class Derived : public Base {
//Member functions of Derived are not friends of Fred
};
In the following example, an EggCarton is not supposed to have more than a
dozen eggs (numEggs_ <= 12). Class EggCartonFiller is trusted not to violate
the semantics of an EggCarton, so EggCarton makes EggCartonFiller a friend.
This friendship allows EggCartonFiller::addAnEgg() to access
EggCarton::numEggs_.
class EggCartonFiller; // Tell the compiler that
// "EggCartonFiller" is a class
class EggCarton {
public:
EggCarton() throw(); // Creates an empty carton
private:
friend EggCartonFiller;
int numEggs_; // numEggs_ can't exceed a dozen
};
EggCarton::EggCarton()
: numEggs_(0) { }
class EggCartonFiller {
public:
void addAnEgg(EggCarton& carton) throw();
};
void EggCartonFiller::addAnEgg(EggCarton& carton) throw()
{
if (carton.numEggs_ < 12)
++ carton.numEggs_;
}
If friendship were inherited, anyone could create a class derived from
EggCartonFiller and possibly violate the semantics of an EggCarton.
class SubversiveFiller : public EggCartonFiller {
public:
void violateEncapsulation(EggCarton& carton) throw();
};
void SubversiveFiller::violateEncapsulation(EggCarton& carton) throw()
{
#ifdef GENERATE_ERROR
carton.numEggs_ = 13; //< -- 1
#endif
}
(1) Compile-time error: Can't access carton.numEggs_
Regards,
Muhammad Ajmal
_____
From: [email protected] [mailto:[EMAIL PROTECTED] On Behalf Of
Aswin Rajamannar
Sent: Friday, February 29, 2008 2:22 PM
To: [email protected]
Subject: Re: [c-prog] friend function behaviour
Friend functions, though member function of a class, can be used for all
classes within the scope. Even the derived classes comes under this. Derived
class does not inherit friend function, but it can access it just like other
members. I'm not sure if I'm right (I too am only a beginner). pls correct
me if i'm wrong.
On 2/29/08, samba8514 <[EMAIL PROTECTED] <mailto:samba8514%40yahoo.com> com>
wrote:
>
> this is the point i studied from C++ Complete Reference (3rd Ed.).pdf
>
> First, a derived
> class does not inherit friend functions.
>
> page no:302(335/1041)
>
> i want one prog to prove this statement
> pls try this once
>
>
>
[Non-text portions of this message have been removed]
[Non-text portions of this message have been removed]