简体   繁体   中英

Dynamic binding in C++?

I need some clarification on dynamic binding in C++.
I explain my problem.
I have to implement a dictionary by using a binary search tree. I decided to implement also an AVL tree (self-bilancing binary search tree). I have successfully implemented the two classes: BST (binary search tree) and AVL that extends BST. My program works correctly.
My goal is to have only one pointer that I can switch from class BST to class AVL asking to the user "whitch structure would you like to use?" at the start of the program.
The rest of the code is the same because BST and AVL have the same methods name (even if they do different things -> overriding).
I've reached my goal by this way:

cout << "whitch structure would you like to use? [1] for BST, [2] for AVL"; 
short choise;  
cin >> choise;

BST a;  
AVL b;  
BST* dictionary;

if (choise == 1)
    dictionary = &a;  
else if (choise == 2)
    dictionary = &b;    
.  
.  
.  
dictionary->doSomething();

My question is:
Is this a correct way to proceed? And is this an example of dynamic binding?

Thank you for your attention and I'm sorry if I have not explained my problem correctly, but this is my first post on this wonderful site!

Is this an example of dynamic binding?

Assuming AVL derives BST , then yes.

Is this a correct way to proceed?

Assuming AVL derives BST , then yes.

Is it the best way to proceed? Well, perhaps not. You're always instantiating both kinds of tree, even if only one is ever used. This seems wasteful.

The more common approach is to actually conditionally construct them:

std::unique_ptr<BST> dictionary;
if (choise == 1)
    dictionary.reset(new BST());  
else if (choise == 2)
    dictionary.reset(new AVL());

// ...

assert(dictionary.get());
dictionary->doSomething();

Unless you're mortally allergic to dynamic allocation, or you don't have a heap on your system, or you're doing this stuff in a hyper-tight loop somewhere, this approach is more conventional.

Ultimately, though, it's pretty much the same thing.

如果AVL类是公共继承自BST类的,那么是的,这是正确的。

This is an example of Polymorphism , dynamic binding is the expression of polymorphism at run time.

Since AVL is-a BST, you should definitely have AVL publicly inheriting from BST. Then yes, you application will be able to treat both types polymorphically.

Another approach might be to separate the algorithm for balancing from the general BST data structure. Eg you could use AVL or RBT or indeed something else.

the algorithm to use could be passed in the constructor.

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