3

Why Doesnt C++ allow This

void insertData (T data1,Tree<T> *tree=TreeTop);

Passing A Value As a Default Parameter is allowed but why not a variable as a default paramaeter....??

class BinaryTree
{
    private :

    Tree<T> *TreeTop;
    unsigned int numberOfElements;

    public :
            void insertData (T data1,Tree<T> *tree=TreeTop);
            // Only Prototype For Question Purpose
    }
Rohith R
  • 1,309
  • 2
  • 17
  • 36

2 Answers2

1

You could make an overload like this:

void insertData(T data1) {
    insertData(data1, TreeTop);
}

void insertData(T data1, Tree<T> *tree) {
    // Code
}
  • yeah i did the same only...just wanted to know what technical difficulties does the compiler faces to pass a variable as a default argument... – Rohith R Jun 18 '14 at 08:38
0

This will work if you make TreeTop static:

class BinaryTree
{
    private :

    static Tree<T> *TreeTop;
    unsigned int numberOfElements;

    public :
            void insertData (T data1,Tree<T> *tree=TreeTop);

}

In that case, it will be a class-level default for the "insertData" method call. If you want an instance-level default, you will have to instead do something like

class BinaryTree
{
    private :

    Tree<T> *TreeTop;
    unsigned int numberOfElements;

    public :
            void insertData (T data1,Tree<T> *tree=NULL);

}

Then, in your implementation, do

public void BinaryTree::insertData(T data1, Tree<T> *tree)
{
    if (tree==null) tree=TreeTop;
    ...
}
T3am5hark
  • 856
  • 6
  • 9
  • you mean `nullptr` (or `NULL` for C++03) instead of `null`. – Jarod42 Jun 18 '14 at 08:49
  • It assumes that `nullptr` is not a *valid* input. – Jarod42 Jun 18 '14 at 08:50
  • @Jarod42 - Yep, I've got C# on the brain ~ corrected. Also correct on second point - assumes null is not valid input. If null is valid, then previous poster's overload approach will get it. – T3am5hark Jun 18 '14 at 08:53