简体   繁体   中英

How is the conversion from one class to another possible?

I'm learning BST in data structures. I encountered some code in my textbook that I can't understand.

I've simplified it this way:

Tree should be the binary search Tree.

Node is a nested struct in Tree.

Element is used to store data in the Node.(All of them originally should be template class and node originally should also store key, etc. However in this case I omit these details.)

#include <iostream>

class Element {

};

class Tree {
   public:
    struct Node {
        Element *element;
    };

    Node *root;
    Element* find() {
        Node *tmp = root;
        return (Element *) tmp; // this line
    }
};

int main() {
    Tree t;
    std::cout << t.find() << '\n';
    return 0;
}

In line 16(as commented), what's the function of (Element *) ? I suppose it's a conversion, but how is the conversion between two different classes possible? (if my assumption is right)

In line 16(as commented), what's the function of (Element *) ?

I suppose it's a conversion

That's right. It's an explicit conversion; also called C-style cast.

but how is the conversion between two different classes possible?

Conversion between two classes is possible in two cases: One class has a converting constructor, or the other has a conversion operator.

Node and Element have neither converting constructors nor conversion operators, so they are not convertible to each other. However, the shown program doesn't convert between classes. It converts between pointers to classes.

C-style cast performs one or a combination of static cast, const cast and reinterpret cast depending on what the source and target types are. For pointers to unrelated classes, there is no valid static cast, so reinterpret cast is performed.

Reinterpreting a pointer to an unrelated type results in a pointer that has only limited uses. You can compare its equality to another pointer or convert it back to the correct type, but indirecting such reinterpreted pointer has undefined behaviour except in few cases. This is not one of the exceptional cases, so we can conclude that the "function" of the cast is to make the result mostly useless.


PS There is another problem. t.root was never initialised, so it has indeterminate value, and so Node *tmp = root reads an indeterminate value, and so the behaviour of the program is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM