Reputation: 39
The question comes up with me when reading chapter 13 of accelerated c++.
There are three classes involved in this question, e.g. class Core
, class Grade
and class Student_Info
. Core
is the base class. Grade
is the derived class inherited from Core
. Student_info
is the handle class.
In order to define copy constructor for Student_info
, we need a virtual clone
function in class Core
and we also need to redefine it in class Grade
. Both functions are under the protected
label. To access the protected clone
function of Core
, the handle class Student_Info
must be nominated a friend class of Core
.
However, its says that we don’t need to nominate Student_Info
as a friend of Grade
to access its clone function because we can access it only through virtual calls to Core::clone
. I’m really confused about this. I don’t know how can Student_Info
access Grade
’s clone
function. If cp (of type Core*
) points to an object of class Grade
, why can s.cp->clone()
work? Can some give me detailed elaboration of this?
Relevant parts of code:
class Core {
friend class Student_info;
protected:
virtual Core* clone() const { return new Core(*this); }
};
class Grad {
protected:
Grad* clone() const { return new Grad(*this); }
};
Student_info& Student_info::operator=(const Student_info& s) {
if (&s != this){
delete cp;// cp is of type Core*
if (s.cp)
cp = s.cp->clone();
else
cp = 0;
}
return *this;
}
Upvotes: 0
Views: 40
Reputation: 14977
Student_info
is a friend to Core
, so it is able to access Core::clone()
. This is why s.cp->clone()
works. Where the call is dynamically dispatched is internal and irrelevant.
To which method the call is dynamically dispatched cannot be known a priori (statically). The compiler does not know it, let alone checking its access modifier.
Upvotes: 1
Reputation: 275555
Private protected and public protect ways of naming things, not the things themselves.
You are naming the base class clone; you only need permission to access it by that name. The fact it is actually something else is not relevant.
Upvotes: 0