OOP344 Multiple inheritance, casting and temporary nameless objects
Please note the following conversation when dealing with casting in C++:
svn://zenit.senecac.on.ca/oop344/trunk/A/05-Aug05/minh4.cpp
<Neg206> Hello Fardad <fardad> Neg206: Hi Neg206 <Neg206> On friday on lecture August 5 <Neg206> minh4.cpp after we set to B to 1234 ? fardad is checking out the note <Neg206> when we print the A(C(d)) is should print to 123456 or -123 <fardad> so, on first look, it you would say that it should print 123456,..... <fardad> (Line 71 : A(B(d)).set(123456);) <fardad> but it won't, <fardad> it will print -123 <Neg206> yes why? <fardad> because A(whatever) is not a call to a constructor(a constructor is not a function and can not be called), but it is creating a temp nameless object <fardad> so you are setting data to 123456, but <fardad> you are setting data of a nameless object who is going to die right at the end of line 71 <fardad> and the original A part of d object remains the same <Neg206> yes die after simicolon so data is still -123 <fardad> yes, but if you replace line 71 with <fardad> d.B::A::set(123456); <fardad> then you are NOT setting a temp nameless but "A part of object d" <Neg206> yes thank you
#include <iostream>
using namespace std;
class A{
private:
int data;
public:
A(int data=-123){
this->data = data;
}
void set(int data){
this->data = data;
}
int print(){
cout<<"A: "<<data<<endl;
return data;
}
};
class B: virtual public A{
private:
int data;
public:
B(int data = -2):A(data*4){
this->data = data;
}
int print(){
A::print();
cout<<"B: "<<data<<endl;
return data;
}
};
class C:virtual public A{
private:
int data;
public:
C(int data = -3):A(data*3){
this->data = data;
}
int print(){
A::print();
cout<<"C: "<<data<<endl;
return data;
}
};
class D: public B, public C{
private:
int data;
public:
D(int data):B(10),C(20){
this->data = data;
}
int print(){
B::print();
C::print();
cout<<"D: "<<data<<endl;
return data;
}
};
int main(void){
D
d(100);
d.print();
A(d).print();
//A(B(d)).set(123456); this will not set the data of "A part of d" please read the comments below...
d.B::A::set(123456);
A(C(d)).print();
return 0;
}