Hello :)
I learn C++ from a book,and now I learn about inheritance.
I read this in the book(I try to translate correct):
"Another source of problems is that many function of the "ABC" class are returning or taking as argument a "ABC" object,not a "DEF" object."
DEF is derived class of ABC class.
This seem to be logical,but I tried to test that in a program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
class base{
public:
base sub(const base&);
};
class deriv : public base{};
base base::sub(const base& obj){
std::cout<<"heiho"<<std::endl;
return obj;
}
int main(){
base bobj;
deriv dobj;
dobj.sub(dobj);
//dobj=dobj.sub(dobj);
std::cin.sync();
std::cin.ignore();
return 0;
}
|
Line 22 and 23: I can't understand why line 22 is correct.The function "sub" takes as argument a "base" object , not a "deriv" , though it's working. And I have no constructor in the "deriv" class that takes a "base" object or vice versa.
But line 23 isn't working.
It seems that the compiler can convert a "deriv" object in a "base" object,but vice versa not. Is this true ?
Thanks in advance.
Have a sunny day !