• 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

    • I don't care about browser benchmarks. It's loads pages nearly instantly and doesn't really feel slow at all to me. Anyway I care more about features and stability and so far I'm satisfied. Plus I wouldn't use Edge if Microsoft paid me.
    • And the big problem we have seen with government organizations is the incredibly slow accountability. In the private space, the need to turn a profit forces the issue. That may not always be healthy, but it is swift. The best working example of a government organization is the USPS, but that is in part because it was created to operate like a business, with its own budget and revenue. That model may not work in every case, for example, I wouldn't want law enforcement under pressure to find revenue, but in some cases it does work.
    • Hell Let Loose, and A Little to the Left, and more join Xbox Free Play Days this weekend by Pulasthi Ariyasinghe Microsoft lets every Game Pass subscriber jump into fresh games every weekend for no extra cost, and it's time for another bunch of games to join the fray. The latest update offers Xbox Game Pass Ultimate, Standard, and Core subscribers access to three games: Dragon Ball Xenoverse 2, Hell Let Loose, and A Little to the Left. As usual, any progress made during the weekend also carries over automatically if you decide to purchase a game afterward. From the trio, Hell Let Loose is for shooter fans, offering 50 versus 50 PVP battles across various realistic World War II fronts. However, the gameplay is a much more hardcore experience compared to other shooters on the market. The title features infantry, tanks, and artillery warfare, with 14 roles available that offer different weapons and teamwork-related equipment. Next, Dragon Ball Xenoverse 2 comes in, touting its ties to the massive anime franchise. The title has players time-traveling to the past as a custom Dragon Ball character to make sure historical moments from the storyline happen just as fans remember. While the world itself is a massive one, fights happen in 3D arenas, taking cues from notable locations in the anime universe. If both those games are a bit too action-heavy, A Little to the Left is a cozy puzzle experience that aims to settle your perfectionist needs. The game has you sorting, stacking, and organizing household items from their awkward locations to more pleasing and organized placements. The controls mostly involve drag-and-drop operations, and some puzzles even have multiple solutions for neatness. Here are the three latest Free Play Days games and their supported platforms: Hell Let Loose - $24.99 (Xbox Series X|S, PC) DRAGON BALL XENOVERSE 2 - $5.99 (Xbox Series X|S, Xbox One, PC) A Little to the Left - $7.49 (Xbox Series X|S, Xbox One, PC) This Free Play Days promotion will end on Sunday, June 8, at 11:59 pm PT. Following this, expect another round of games to enter the program next Thursday.
    • AMD 25.6.1 driver out with RX 9060 XT support and a lot more FSR 4 games by Pulasthi Ariyasinghe A brand-new hardware launch is happening today for AMD, and to make sure its new GPUs are running properly, a new graphics driver has also landed right alongside it. The AMD Software: Adrenalin Edition 25.6.1 driver lands with support for the RX 9060 XT and the AMD Radeon AI PRO R9700, while also finally updating the number of games that support its AMD FidelityFX Super Resolution 4 upscaling technology. The consumer space-targeted RX 9060 XT graphics card comes in 8GB and 16GB flavors starting at $300 and $350 price points, respectively. Check out our launch coverage for this RDNA 4 GPU for more details here. At the same time, the AMD Radeon AI PRO R9700 comes in for handling professional workloads with a whopping 32GB of VRAM. While support for this card has already arrived with the latest driver, AMD is expecting to ship the product sometime in July 2025. The driver has also added official support for Onimusha 2: Samurai's Destiny Remaster as well, the Capcom-developed action game from last month. As for fixes, AMD has said that it has resolved reversed Quality and Performance selections in the Radeon Boost UI, as well as Le Mans Ultimate performance issues on RX 9070 series GPUs. There are quite a few known issues AMD is still working on: Stutter and lower than expected performance may be observed when using alt-tab and streaming to Discord with multiple monitors. Intermittent application crash or driver timeout may be observed while playing Marvel Spiderman 2 with Ray Tracing enabled on Radeon™ RX 9060 XT. Intermittent application crash may be observed when first launching The Last of Us Part 1 on Radeon™ RX 9060 XT graphics products. Stutter may be observed while playing games with some VR headsets at 80Hz or 90Hz refresh rate on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Users experiencing this issue are recommended to change the refresh rate as a temporary workaround. Intermittent system or application crash may be observed while playing Cyberpunk 2077 on some AMD Radeon™ Graphics Products such as the Radeon™ RX 7000 series. Intermittent application crash or driver timeout may be observed while playing Monster Hunter Wilds with Radeon™ Anti-Lag and Instant Replay enabled. Artifacts or corruption may appear while playing Battlefield™ V on Radeon™ RX 7000 series graphics products. Stutter may be observed while playing Call of Duty®: Warzone™ Season 03 ‘Verdansk’ map on some AMD Graphics Products. Stutter and lower than expected performance may be observed while playing 4K resolution YouTube videos in Chromium. Users experiencing this issue are recommended to play videos in full screen as a temporary workaround. Texture flickering or corruption may appear while playing The Elder Scrolls IV: Oblivion Remastered with AMD FidelityFX™ Super Resolution enabled on Radeon™ RX 9070 XT. Users experiencing this issue are recommended to disable AMD FidelityFX™ Super Resolution as a temporary workaround. As for FSR 4, these games are now supported by the popular upscaling tech for gaining more frames: Deadzone: Rogue Rem Survival F1 25 Runescape: Dragonwilds Frostpunk 2 Star Wars Outlaws Legacy: Steel & Sorcery Steel Seed Lords of the Fallen Stellar Blade Planetaries Virtua Fighter 5 R.E.V.O QANGA Wild Assault The complete list of games with FSR 4 support, as well as upcoming implementations, can be found on AMD's support page here. The WHQL-certified AMD Software: Adrenalin Edition 25.6.1 driver can now be downloaded from the AMD Software app as well as the changelog page on its official website here.
  • 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
      406
    2. 2
      +FloatingFatMan
      181
    3. 3
      snowy owl
      176
    4. 4
      ATLien_0
      170
    5. 5
      Xenon
      135
  • Tell a friend

    Love Neowin? Tell a friend!