flamexx7 said:
In my book there is a question about "properly" creating a copy constructor
of child class during inheritance. Is it ok to use upcasting here ? I've
used upcasting and it seems to work fine.
#include <iostream>
using namespace std;
class A{
int a;
public:
A(int temp=0):a(temp){}
A(A& right):a(right.a){}
};
class B
ublic A{
int b;
public:
B(int temp=0):b(temp){}
B(B& right){A(*this);
b=right.b;
}
};
int main(){
B b;
B b1=b;
cin.get();
}
It compiles, but, although I don't know what you want it to do, it
doesn't look like it does what I think you want it to do.
In the copy constructor of B, you initialize A with *this, before B is
initialised. So, if you in main() do:
int main(){
B b(10);
B b1=b;
you'll get a B1 who's a is uninitialised (that's what it looks like to
me. I just compiled it with g++-3.4.4, and that shows that b1.a
initialised to whatever default value I put in A::A(int temp=xxx)
constructor.
#include <iostream>
using namespace std;
class A{
int a;
public:
A(int temp=123):a(temp){}
A(A& right):a(right.a){}
void show(){
cout<<"A: a="<<a<<endl;
}
};
class B
ublic A{
int b;
public:
B(int temp=124):b(temp){}
B(B& right){A(*this);
b=right.b;
}
void show(){
A::show();
cout<<"B: b="<<b<<endl;
}
};
int main(){
B b(10);
b.show();
B b1=b;
b1.show();
}
Output:
A: a=123
B: b=10
A: a=123
B: b=10
Oh, and BTW, why didn't you do as suggested, make the ref arguments
const?