Reputation: 3331
Code:
#include<iostream>
using namespace std;
class B{
public:
int b;
B(int x):b(x){
cout << "B() Constructor " << endl;}
B(const B& m):b(m.b){
cout << "B(const B&) copy constructor "<< endl;}
};
class D:public B{
public:
D(int x):B(x){
cout << "D() Constructor " << endl;}
D(const D& n):B(n){ // at this point n should be casted to B object !!?
cout << "D(const D&) copy constructor " << endl;}
operator B(){
cout << "operator B" << endl;
return B(this->b);}
};
int main(){
D ob(1);
cout << "---" << endl;
D oc=ob;
}
Output:
B() Constructor
D() Constructor
---
B(const B&) copy constructor
D(const D&) copy constructor
Questions:
1) if I didn't supply my D
copy constructor, the default copy constructor of D
must initialize the Base object by calling B
copy constructor. My question is what is the argument that copy constructor of B
will take ? is it a D
object and then it will be casted to a B
object ?
2) in the copy constructor of D
, I initialized B
with a D
object n
, and there was no calling to the operator B()
which proof that the object n
of type D
didn't get casted to B
, so it can be passed as an argument to the B
copy constructor. is there any explanation for this behavior ?
Upvotes: 0
Views: 134
Reputation: 76245
First, a cast is something you write in your code to tell the compiler to do a conversion. There are two categories of conversions: implicit and explicit. Implicit conversions will be done when needed, without a cast. Explicit conversions require a cast. What you're talking about here is an implicit conversion, not a cast.
And the answer is that there is an implicit conversion from a reference to a derived type into a reference to a base type. It's that simple: n is a D&, and it can be passed to a function that takes a B& simply by implicitly converting its type.
Upvotes: 4