1

I am building a LinkedList in C++.
Signature for addNode function:

const bool LinkedList::addNode(int val, unsigned int pos = getSize());  

getSize() is a public non-static member function:

int getSize() const { return size; }

size is a non-static private member variable.
However, the error that I am getting is a nonstatic member reference must be relative to a specific object

How do I achieve this functionality?

Just for reference, here's the whole code:

#pragma once

class LinkedList {
    int size = 1;
    struct Node {
        int ivar = 0;
        Node* next = nullptr;
    };
    Node* rootNode = new Node();
    Node* createNode(int ivar);
public:
    LinkedList() = delete;
    LinkedList(int val) {
        rootNode->ivar = val;
    }
    decltype(size) getSize() const { return size; }
    const bool addNode(int val, unsigned int pos = getSize());
    const bool delNode(unsigned int pos);
    ~LinkedList() = default;
};


Some other tries include:

const bool addNode(int val, unsigned int pos = [=] { return getSize(); } ());
const bool addNode(int val, unsigned int pos = [=] { return this->getSize(); } ());
const bool addNode(int val, unsigned int pos = this-> getSize());

The current workaround I am currently using:

const bool LinkedList::addNode(int val, unsigned int pos = -1) {
    pos = pos == -1 ? getSize() : pos;
    //whatever
}
0

1 Answer 1

4

The default argument is provided from the caller side context, which just doesn't know which object should be bound to be called on. You can add another wrapper function as

// when specifying pos
const bool LinkedList::addNode(int val, unsigned int pos) {
    pos = pos == -1 ? getSize() : pos;
    //whatever
}

// when not specifying pos, using getSize() instead
const bool LinkedList::addNode(int val) {
    return addNode(val, getSize());
}
Sign up to request clarification or add additional context in comments.

4 Comments

@d4rk4ng31 One function with the pos argument (but without a default value), and one without a pos argument. The one without calls the function with (as shown in this answer).
@d4rk4ng31 that's not unnecessary reproducal of code if only the top-most function is doing the main part. All other functions are calling up to them
@d4rk4ng31 Because as the default argument this pointer needs to be provided at caller side context, but there isn't.
@d4rk4ng31 It may be helpful to look at how C++ classes are laid out in memory, especially functions. There is only one set of class functions in memory for all objects of the same class type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.