Feb 9, 2013 at 2:40am UTC
Hello
So im working on a linked list that instead of the traditional integer value for a data, i'm using my own class. Unfortunately when i do this, i cant seem to retrieve my data from my Node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
#include "Customer.h"
class Node {
// TO DO:: Fill in.
//Constructors and destructor
public :
Node();
Node(int atime, int ttime);
Node(int atime, int ttime, Node* nd);
~Node();
Customer get_cust();
// Public attributes
Customer cust;
Node* next;
};
#include <iostream>
#include "Node.h"
#include "Customer.h"
Node::Node()
{
Customer cust = Customer(0,0);
next = 0;
}
Node::Node(int atime, int ttime)
{
Customer cust = Customer(atime, ttime);
next = 0;
}
Node::Node(int atime, int ttime, Node* nd)
{
Customer cust = Customer(atime, ttime);
next = nd;
}
Node::~Node()
{
}
Customer Node::get_cust()
{
return cust;
}
/////////////////
class Customer {
// TO DO:: Fill in.
public :
//Constructors and destructor
Customer();
Customer(int artime, int trtime);
//Setters
void set_atime(int time);
void set_ttime(int time);
//Getters
int get_atime() const ;
int get_ttime() const ;
private :
// Private attributes
int atime;
int ttime;
};
#include "Customer.h"
//Constructors
Customer::Customer()
{
atime = 0;
ttime = 0;
}
Customer::Customer(int artime, int trtime)
{
atime = artime;
ttime = trtime;
}
//Setters
void Customer::set_atime(int time)
{
atime = time;
}
void Customer::set_ttime(int time)
{
ttime = time;
}
//Getters
int Customer::get_atime() const
{
return atime;
}
int Customer::get_ttime() const
{
return ttime;
}
In my main code, I've been trying something like
1 2 3 4
Node* c = new Node(1,2)
Customer x = c->cust; // or Customer x = c->get_cust();
cout<<x.get_atime()<<endl;
cout<<x.get_ttime()<<endl;
It should be displaying 1 and then 2, but just outputs 0 and 0.
Any input would be greatly appreciated. Thanks!
Last edited on Feb 9, 2013 at 2:47am UTC
Feb 9, 2013 at 8:19am UTC
Hi,
Node* c = new Node(1,2)
Here you have created a node object on heap. Which is initialized by argument (1,2). This will call Node::Node(int atime, int ttime).
Till so far things are fine.
Customer cust = Customer(atime, ttime);
Now you have initialized a local variable cust. Which will be destroyed as you leave the constructor.
Customer x = c->cust;
Here you are trying to get the value of cust from Node member. Which was never assigned values (1,2).
So output is correct as 0,0.
Last edited on Feb 9, 2013 at 8:20am UTC