On Sep 21, 12:07 pm, t <tmt...@Yahoo.comwrote:
Lippman's C++ Primer, 4th ed., p562, dicussion of protected members
seems to be wrong, unless I am misinterpreting things. He says:
"A derived class object may access the protected members of its base
class only through a derived object. The derived class has no special
access to the protected members of base type objects."
He gives the following example:
================================================== =======
class Item_base
{
public:
// stuff omitted
protected:
double price;
private:
std::string isbn;
};
class Bulk_item : public Item_base {
// stuff omitted
};
void Bulk_item::memfcn(const Bulk_item&d, const Item_Base& b)
{
// attempt to use protected member
double ret = price; // ok: uses this->price
ret = d.price; // ok: uses price from a Bulk_item object
ret = b.price; // error: no access to price from an Item_base
}
================================================== =======
Am I right?
No. The description and the example are both correct.
The point to note is this : "a member function can access all (even
private) members of its arguments of the same type"
In your example:
void Bulk_item::memfcn(const Bulk_item&d, const Item_base& b)
{
double ret = price; // uses this->price
ret = d.price; // The argument d is of type Bulk_item which is
same as type of *this. Hence, all members of d are accessible to every
member function of Bulk_item. Hence d.price works.
(Recollect first part of the sentence from book : A derived class
object may access the protected members of its base class only through
a derived object. Thats other part of reason why d.price works. Note
that d.price would not work if you try to access it from a general
global function like "main")
ret = b.price; // (Recollect second part of sentence from the
book : The derived class has no special access to the protected
members of base type objects. Thats why member 'price' of object b,
which is protected, cannot be accessed by general code.)
}
-Neelesh