c++ object instantiated/passed to method as reference or pointer or valueA -
i#ve looked @ couple of posts here on still dont quite it. here's little bit of code (note: wasnt trying implement 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 references aliases. understand primitive types. still dont quite what's big difference between references , pointers when comes object instantiation, other than: - pointers can null - in case of pointers, need call delete @ point
i saw singleton implementation returns pointer object. guess way in case because need teh returned obejct on heap.
but in example? compiles, need use references , need use pointers? difference between returning reference , object , returning pointer object?
for linked lists in c++: use references next , previous nodes?
and in post can return value, in java:
when return pointer, scalar , reference in c++?
so add this:
node list::getnode3(void) { return thenode; }
and call this:
node someothernode = firstlist.getnode3(); std::cout << someothernode.getdata() << std::endl;
which return value, right?
thanks takes couple of minutes provie clarity!
Comments
Post a Comment