Consider the following code:
#include <iostream>
using namespace std;
class B{
public:
B(){}
};
class A
{
public:
A(){}
A(B &b){
}
A(const B &b){
cout<<"cccddd"<<endl;
}
};
int main()
{
B b;
A c(b);
A a;
a=b; //ok
A &ref = b; //error and why???
}
why b assigned to a is ok,but b assigned to ref is illegal???
This will enable you to convert an object of type
Binto an object of typeA. However, a referenceT&cannot be created from another typeL.In your example neither are
AandBthe same type, nor isAa base class ofB, thus both classes aren’t reference-related.Why won’t
A &ref = (A)bwork?The expression
(A) bwill actually create a temporary, which cannot be bound to a normal reference:You would need to a const reference
A const & ref = (A)bfor this.