I#ve already looked at a couple of posts here on SO but I still dont quite get it. Here's a little bit of code (note: I wasnt trying to implement a linked list):
#include <iostream>
class Node
{
int data;
public:
Node(void);
Node(int data);
void setData(int data);
int getData(void);
};
class List
{
Node theNode;
Node* theNode2 = NULL;
public:
List(Node& param, Node* param2);
void addNode(Node& param);
void addNode2(Node* param);
Node* getNode(void);
Node& getNode2(void);
};
Node::Node(void)
{
this->setData(20);
};
Node::Node(int data)
{
this->setData(data);
};
void Node::setData(int data)
{
this->data = data;
};
int Node::getData(void)
{
return data;
};
Node* List::getNode(void)
{
return theNode2;
};
Node& List::getNode2(void)
{
return theNode;
};
List::List(Node& param, Node* param2)
{
theNode = param;
if (param2 != NULL)
{
theNode2 = param2;
}
std::cout << "theNode Data " << theNode.getData() << " " << std::endl;
std::cout << "TheNode2 data " << theNode2->getData() << " " << std::endl;
};
void List::addNode(Node& param)
{
theNode = param;
std::cout << " TheNode data " << theNode.getData() << " " << std::endl;
};
void List::addNode2(Node* param)
{
if (param != NULL)
{
theNode2 = param;
}
std::cout << "TheNode2 data " << theNode2->getData() << " " << std::endl;
};
int main (void)
{
Node firstNode;
Node secondNode(300);
Node* thirdNode = new Node();
// Node* forthNode = new Node(392);
Node fifthNode(2001);
List firstList(firstNode, thirdNode);
List secondList(secondNode, &fifthNode);
Node* asu = firstList.getNode();
std::cout << asu->getData() << std::endl;
delete thirdNode;
delete asu;
Node someNode = firstList.getNode2();
std::cout << someNode.getData() << std::endl;
return 0;
};
I get that references are aliases. I understand that for primitive types. But I still dont quite get what's the big difference between references and pointers when it comes to object instantiation, other than: - pointers can be null - in case of pointers, I need to call delete at some point
I saw a singleton implementation that returns a pointer to the object. I guess this is the only way in this case because you need teh returned obejct to be on the heap.
But in my example? I compiles, but where do I need to use references really and where to I need to use pointers? What is the difference between returning a reference to and object and returning a pointer to an object?
For linked lists in C++: Could I use references for the next and previous nodes?
And in this post they say that you can also return by value, like in java:
When to return a pointer, scalar and reference in C++?
So I could add this:
Node List::getNode3(void)
{
return theNode;
}
and call it like this:
Node someOtherNode = firstList.getNode3();
std::cout << someOtherNode.getData() << std::endl;
which is return by value, right?
Thanks to anyone who takes a couple of minutes to provie some clarity!