Passing variables as default parameters in C ++ function

Why doesnt c ++ resolve this

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

Passing a value as a default parameter is allowed, but why is the variable not a default parameter .... ??

class BinaryTree
{
    private :

    Tree<T> *TreeTop;
    unsigned int numberOfElements;

    public :
            void insertData (T data1,Tree<T> *tree=TreeTop);
            // Only Prototype For Question Purpose
    }
+4
source share
2 answers

You can do the overload as follows:

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

void insertData(T data1, Tree<T> *tree) {
    // Code
}
0
source

This will work if you become TreeTop static:

class BinaryTree
{
    private :

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

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

}

In this case, it will be the default for the class to call the insertData method. If you want to set the default level at the instance level, you will need to 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;
    ...
}
0
source

Source: https://habr.com/ru/post/1545035/


All Articles