• 0

C++ linked list and objects


Question

I have been given an assignment from my uni to create a bank where im to have customers with multiple accounts and different account types, also then add other things like loans etc.

Im having problems getting a linked list to work with the class objects. my aim is to store all the customers details, and account details in the class objects then list all the customers in the linked list instead of using something like an array as we get more marks for using linked lists.

so far i have managed to get it so the customer can be created and pointing to just one account. but i am stuggling with understanding how im to then create the linked list so it connects to the class object.

these are some bits of the code which i have so far:

AssignmentBank.cpp (main)

	Account tempAccount(001, 500, 600, "Current");
	Customer tempCustomer("Fred", 01, 0.5, 'M',"180690", &tempAccount);
	CustomerList CL;	
	CL.addCustomer(&tempCustomer);

with this im not sure if im doing it the correct way, but am i to create the objects then pass in the refference to it, which is then stored in the linked list?

CustomerList.cpp

#include "CustomerList.h"
#include <iostream>

using namespace std ;

CustomerList::CustomerList()
{
    front = back = 0;
}

bool CustomerList::isEmpty()
{
   return front == 0;
}


void CustomerList::addCustomer(Customer *tempCustomer)
{
	Node* insert  = new Node(tempCustomer); 
	if (front == 0)
   {
      back = front = insert;
   }
   else
   {
      back-> next = insert ;      
	   back = back -> next ;
   }
}

CustomerList::removeCustomer()
{
   Customer tempCustomer; Node* temp;

	if (front != 0)
   {
      tempCustomer = front -> customerRef;
      temp = front;
      front = front -> next ;
      delete temp ;
      if (front == 0) back = 0;
      return tempCustomer;
   }
   else return '\0';

}


CustomerList::~CustomerList()
{
   Node * temp;
	while(front != 0)
	{
		temp = front;
		front = front -> next;
		delete temp;  
	}
}


void CustomerList::print()
{
	Node * temp = front;
   if (temp != 0 ) 
   {
	   while (temp != 0)
	   {
		   cout << temp -> customerRef.getName() ;
		   temp = temp -> next;
      }
   }
   else cout << "empty";
   cout << endl;

}

CustomerList.h

#include "Customer.h"

class Node
{
public:
	Node* next;
	Customer customerRef;
	Node(tempCustomer)
	{
		Customer *tempCustomer;
		next = 0;
	}	
};


class CustomerList
{
	Node* front;
        Node* back;
public:
	CustomerList();
	~CustomerList();
	void addCustomer(Customer *tempCustomer);
   removeCustomer( );
	bool isEmpty();
   void print() ;

};

any help at all would be useful.

I have gone to extra classes at uni and asked lecturers over and over but they dont seem to be helping me much.

Link to comment
https://www.neowin.net/forum/topic/955220-c-linked-list-and-objects/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

The problem is your Node class: you have to decide whether you want it to hold copies of Customers or references(pointers) to Customers. Both approaches are valid yet different. If you go with references, you have to ensure that the original Customers remain alive otherwise the references will soon point to nothing. If you go with values (copies), there's no dangling reference issue but of course you encur the performance cost of the copy.

This is basically how I would code it:

struct Node // if you only want public members, use a struct, it's the same thing as class except everything is public by default
{
        Node* m_next;
        Customer& m_customer;
        Node(Customer& customer) : m_next(0), m_customer(customer) {}   
};

And then the addCustomer method would look virtually identical to yours (except I like references better when I can use them):

void CustomerList::addCustomer(Customer& customer)
{
    Node* insert  = new Node(customer); 
    if (front == 0)
   {
      back = front = insert;
   }
   else
   {
      back->next = insert;   
      back = back ->next;
   }
}

  • 0

A struct is a class in C++. They are literally duplicate keywords. The only difference is that default visibility is private in a class, whereas it is public in a struct. So if all it takes to satisfy your teacher is to not use the keyword "struct", change "struct" by "class" and add "public:" before the member declarations. :laugh:

Seriously though, it's not clear to me what your teacher meant by that. The C++ way of doing a linked list is usually:

#include <list>

int main()
{
    // look ma no code
    std::list<int> linkedList;
    linkedList.push_back(1);
    // etc
}

  • 0

thank you, i got it working after playing around a little with what i already had. can now add customers and display them how i need to.

problem is now i want to be able to have multiple accounts for each customer.

at the moment i have:

customer.cpp

Customer::Customer(string tempName, string tempTelNo, double tempInterestRate, char tempSex, string tempDoB, Account *bankAccount)
{
	name=tempName;
	telNo=tempTelNo;
	interestRate=tempInterestRate;
	sex=tempSex;
	DoB=tempDoB;
	accountRef=bankAccount;
}

and an example of creating a customer is:

AssignmentBank.cpp

CL.addCustomer(new Customer("Fred", "01785211211", 0.5, 'M',"110284", new Account(002, 600, 700, "Current")));

thing is i want to be able to make lots of accounts without a limit really.

and if i go to the array option then i cant change the size of the array can i?

can someone point me in the right direction of how i can do this?

  • 0

You need a linked list structure for everything you need a list of - customers, accounts, etc. Rather than duplicating the linked list code for each type of list, look into templating!

When creating your new example customer, you'd do it something like:

Customer* custTmp = new Customer("Fred", "01785211211", 0.5, 'M', "110284");
CustTmp->addAccount(new Account(002, 600, 700, "Current"));
CustTmp->addAccount(new Account(003, 601, 701, "Current"));
//etc
CL.addCustomer(custTmp);
custTmp = 0; //no need to keep a copy of the pointer here in main(), the linked list has it and can handle freeing up memory when necessary, safer to disarm this!

  • 0
  On 23/11/2010 at 00:18, theblazingangel said:

You need a linked list structure for everything you need a list of - customers, accounts, etc. Rather than duplicating the linked list code for each type of list, look into templating!

When creating your new example customer, you'd do it something like:

Customer* custTmp = new Customer("Fred", "01785211211", 0.5, 'M', "110284");
CustTmp->addAccount(new Account(002, 600, 700, "Current"));
CustTmp->addAccount(new Account(003, 601, 701, "Current"));
//etc
CL.addCustomer(custTmp);
custTmp = 0; //no need to keep a copy of the pointer here in main(), the linked list has it and can handle freeing up memory when necessary, safer to disarm this!

I understand how to create them as you have mentioned, just not to sure how to add the references of the accounts to the customer.

  • 0

I haven't used C++ in quite some time, but when I did, I made an arraylist class. Just a doubly linked list... I found it pretty fun to make, and I put it on Google Code.

You can check out the adding method here, among many others: http://code.google.com/p/arraylist/source/browse/trunk/arraylist.cpp#119

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • GeForce NOW adds support for 25 games in June, including Rematch and Dune: Awakening by Pulasthi Ariyasinghe A new month is here, and Nvidia is starting it off with a big GeForce NOW announcement as usual. The latest reveal has support for 25 games that are incoming in June alone, with some highlights including Rematch, The Alters, FBC: Firebreak, Dune: Awakening, and even the Borderlands trilogy from Gearbox and 2K. Just this week alone, Nvidia is adding support for the following ten games for GeForce NOW subscribers: Symphonia (New release on Xbox, available on PC Game Pass, June 3) Pro Cycling Manager 25 (New release on Steam, June 5) Tour de France 2025 (New release on Steam, June 5) Dune: Awakening – Advanced Access (New release on Steam, June 5) 7 Days to Die (Xbox) Clair Obscur: Expedition 33 (Epic Games Store) Cubic Odyssey (Steam) Drive Beyond Horizons (Steam) Police Simulator: Patrol Officers (Xbox, available on PC Game Pass) Sea of Thieves (Battle.net) Nvidia also has plans to add a bunch more games in the rest of June, which is when most of the biggest new releases are coming: Dune: Awakening (New release on Steam, June 10) MindsEye (New release on Steam, June 10) The Alters (New release on Steam and Xbox, available on PC Game Pass, June 13) Architect Life: A House Design Simulator (New release on Steam, June 19) Crime Simulator (New release on Steam, June 17) FBC: Firebreak (New release on Steam and Xbox, available on PC Game Pass, June 17) Lost in Random: The Eternal Die (New release on Steam and Xbox, available on PC Game Pass, June 17) Broken Arrow (New release on Steam, June 19) REMATCH (New release on Steam and Xbox, available on PC Game Pass, June 19) DREADZONE (New release on Steam, June 26) System Shock 2: 25th Anniversary Remaster (New release on Steam, June 26) Borderlands Game of the Year Enhanced (Steam) Borderlands 2 (Steam and Epic Games Store) Borderlands 3 (Steam and Epic Games Store) Easy Red 2 (Steam) The company has a tendency to add many more games to its cloud gaming service outside of these early announcements, so check back as weeks go by to see what's new. Steam Deck owners recently received a better way of using GeForce NOW too, all thanks to a dedicated app. As summer continues, don't forget that the GeForce NOW 40% off sale is still active too, with Nvidia cutting the price of the Performance membership plan until July. As always, keep in mind that unlike subscription services like Game Pass, a copy of a game must be owned by the GeForce NOW member (or at least have a license via PC Game Pass) to start playing via Nvidia's cloud servers.
    • Thought I'd quote myself as reference to what was happening yesterday. I wasn't getting the pop up then in Firefox, but I did just now using it.
    • With DARPA the military can do their own research and then the tech can enter the public domain and benefit the people. If we use public money to buy privatized tech then we don't get that benefit and even worse we will probably pay higher prices in the end. Unfortunately we are ditching NASA for private tech. If you look at all of the technologies developed by NASA that benefit us, you can see why going private can be a huge loss and jack up prices for consumers when private patents are involved. This could have a detrimental effect on innovation by monopolizing certain advancements and reduce access to advancements for the average person, even though our tax dollars would be funding these advancements.
    • Is Microsoft saying that here? Because I don't see it anywhere. It's just a dumb article talking about some new screen, that's all.
  • Recent Achievements

    • Week One Done
      jbatch earned a badge
      Week One Done
    • First Post
      Yianis earned a badge
      First Post
    • Rookie
      GTRoberts went up a rank
      Rookie
    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      405
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      175
    4. 4
      ATLien_0
      170
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!