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
}
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());
}