I’m trying to better understand the differences between pointers and references in C++. Coming from a Java background, I was expecting references in C++ to be similar; I expected a pointer minus the pointer arithmetic. However, I have been very disappointed and, at times, confused. After some reading I thought I understood references to be pointers without pointer arithmetic and that can never be set to NULL. To test what I’ve learned I decided to start coding. However, I came across this problem and I do not understand why my code does not compile.
Here is what I was trying:
3 void test(biNode*& bn)
4 {
5 string& s("another test");
6 bn = new biNode(s);
7 printf("Just Checking: %s\n", bn->getObject().c_str());
8 }
9
10 int main()
11 {
12 biNode* bn;
13 test(bn);
14 printf("Just Checking: %s\n", bn->getObject().c_str());
15 }
And here is the my ‘biNode’ header:
1 #include <string>
2 #include <iostream>
3
4 using namespace std;
5
6 class biNode
7 {
8 public:
9 biNode(string& s);
10 string& getObject();
11 private:
12 string& obj;
13 };
With corresponding definitions:
1 biNode::biNode(string& s) : obj(s)
2 {}
3 string& biNode::getObject()
4 {
5 return this->obj;
6 }
Attempting to compile this produces the following error:
./test.cpp: In function `void test(biNode*&)':
./test.cpp:5: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'const char*'
I do not understand how ‘string& s(“another test”);’ is not valid. Can anyone explain this please?
Thanks in advance!
You can’t initialize a non-const reference with anything but an existing object of the same type, which the reference will then alias. But your class
biNodecontains a reference member, too, and so you must only initialize abiNodeinstance with an object that exists for as least as long as the node instance itself!Here’s an example that demonstrates how you might use the
biNodein a sane way:A sensible version of your
testfunction might look like this: