can anybody tell me what is type casting of classes and where it is used?
I googled it and I found a program on this website but I did not understand
it, can anybody tell me line by line?
PS: I am a beginner and really interested to learn more..
// implicit conversion of classes:
#include <iostream>
usingnamespace std;
class A {};
class B {
public:
// conversion from A (constructor):
B (const A& x) {}
// conversion from A (assignment):
B& operator= (const A& x) {return *this;}
// conversion to A (type-cast operator)
operator A() {return A();}
};
int main ()
{
A foo;
B bar = foo; // calls constructor
bar = foo; // calls assignment
foo = bar; // calls type-cast operator
return 0;
}
Line 19: Creates an instance of A called foo. Note that class A is empty and rather pointless.
Line 20: Creates an instance of B called bar using B's constructor at line 10. This constructor is empty, so we don't know how B is constructed from A.
Line 21: Calls B's assignment operator at line 12. The assignment function is essentially empty, so we don't know how A (foo) is transformed to B (bar).
Line 22: B is cast to A using the cast operator function at line 14. The function constructs an instance of A and returns that.