user3699677
user3699677

Reputation: 25

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!

Upvotes: 0

Views: 263

Answers (4)

Angus Comber
Angus Comber

Reputation: 9708

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.

Upvotes: 0

quantdev
quantdev

Reputation: 23793

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.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

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.

Upvotes: 5

Adi Shavit
Adi Shavit

Reputation: 17265

If the AVL class publicly inherits from the BST class, then, yes, that is correct.

Upvotes: 0

Related Questions