what is type casting of classes and where is it used??

hi,

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..

thank you


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  // implicit conversion of classes:
#include <iostream>
using namespace 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;
}
The comments on lines 20-22 are rather clear.

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.
Thanks for reply

I particularly didn't get line number 10, I did get that it is constructor but what is in the parenthesis. I mean what is "const A& x" ??

It's a const reference to an object of type A.
Topic archived. No new replies allowed.