C++/Heritage Question
Expert: vijayan - 11/26/2008
QuestionDear Vijayan,
Below is an example I took from a book.
Could you confirm that out of those 8 statements below, only the 3 I marked are errors?
class Base{
public:
void am(){...};
.....
};
class Derived{
public:
void af(){...};
.....
};
void gm(Base b){...}
void gf(Derived d){...}
Base b;
Derived d;
gm(b);
gm(d); // error
gf(b); //error
gf(d);
b.am();
d.am();
b.af();// error
d.af();
thanks.
Answeri presume, you intended
class Derived : public Base { .... };
and that Base and Derived are default constructible, Base is copy constructible.
with the above assumptions,
Base b;
Derived d;
gm(b); // ok, exact match
gm(d); // ok, convert Derived to Base (slice)
gf(b); //error, no conversion from Base to Derived
gf(d); // ok, exact match
b.am(); // ok, call member function of Base
d.am(); // ok, call inherited member function
b.af(); // error, af is not a member of base
d.af(); // ok, call member function