Conversion of objects in c++

118 views Asked by At

Question:How a class type can be changed to another class type?

My answer:

       X is a object of class X
       Y is a object of class Y

        x=y;

Is this answer correct? can a class type can be changed to another class type by equating its object to other class object?

1

There are 1 answers

1
user4581301 On

When you run across a problem that can be tested with a very simple program, you write the program and try it out.

What a = b does can be tested very easily.

class A
{
}

class B
{
}

int main()
{
    A = B; 
}

This fails because A and B are just abstract concepts at this point.

int main()
{
    A a;
    B b;
    a=b; 
}

This attempts to copy data of type B into a space of type A. The compiler will not allow this because the square peg does not fit in the round hole any better in software than it does in real life. You can tell the compiler that you will make b fit in a by creating an = operator in A that takes B as an argument, but A is still A. Thank you Ayn Rand.

Why is this? When you made an A, you got a certain amount of memory to hold that A and entered into the contract defined by class A that certain things were going to go into certain places. Break that contract and bad things will happen.

You can do sick things we often had to do in more primitive times such as typecast A into B:

A a;
B b;
*((B*)&a) = b;

but A is still A and you just forced a B-shaped object into its space. What happens to the program when this happens? I'll quote from the classics:

We die.

-- Lord Kril, The Last Starfighter

But it might take a while and look like it worked. A is still A, only now it is a broken A waiting for the opportunity to crash your program.

If you want an A to now be B, make a new B and use your = operator to copy what it can from the A into the new B.

You can also take advantage of classes with common ancestry behaving in a similar fashion, say

class base
{
public:
    int getBaseval()
    {
        return baseval;
    }
private:
    int baseval;
}

class A: public Base
{
}

class B: public Base
{
}

You can count on A and B to both have baseval and return baseval when getBaseval is called, but that's the best you can hope for. You cannot turn A into B or into Base. You can treat A like Base, but it is still A. A can do something completely different from Base or B with a function that they all have (read up on the virtual keyword), but it will still have that function. It will still be an A.