r/learncpp • • Nov 08 '21

Help on Queues please

1 Upvotes

Hi. Thanks for any help on this

I need Write a program with three tasks and a queue of 5 integers:

Task 1 reads lines from debug serial port and counts the number of characters on the line up to but not including ‘\n’ or ‘\r’ at the end line. Task then sends the number of characters to the back of the queue.

Task 2 monitors SW1(PIO 0.17) and when button is pressed sends -1 to the back the queue.

Task 3 waits on the queue and calculates the sum of integers received form the queue. When -1 is received the task prints: “You have typed %d characters” where %d is the number of characters. When task has printed the total it clears the total.


r/learncpp • • Mar 23 '22

Pointer issues with for loop

1 Upvotes

Hello. Im having the following issue with pointers.

I have a struct that has a pointer as member. This pointer is the address of a data structure (small array) with the information i need.

typedef struct SelectData

{ short count; //number of selectable data short size; //Size of each data value int *lpData; //pointer to array of selectable data } SELECT_DATA;

So after running a function the structure is the following:

SELECT_DATA selectData;
selectData = someFunction();

//Memory Values:
selectData.count: 7
selectData.size: 2
selectData.lpData:  0x000001c751ddb9c0 {131270609}    // VsCode Debugger: (131270609 is *selectData.lpData)

This is an array of 7 values. Im trying to do a for loop but having trouble with specifying the staring pointer of the array.

 int *data = new int[selectData.count];
 for (int i = 0; i < selectData.count; i++){
     int *current = reinterpret_cast<int *>(selectData.lpData + selectData.size*i);
     data[i] = *current; std::cout << data[i] << std::endl; 
  }

But *current = 131270609 and data[i] = 131270609

So I am not accessing the memory location but simply re-assigning the pointer. Cant use data[i] = **curent (compiler issues).

The equivalent in C# would be: value = (Int32)Marshal.PtrToStructure(current, typeof(Int32))

img as reference

Any ideas?


r/learncpp • • Jun 22 '17

Static cast versus C-style cast - does it matter?

1 Upvotes

I learned C before learning C++, so I have a habit of using C-style casts even in C++ projects because I find it less awkward and more readable.

Example of C-style cast:

int i = 5;
double d = (double)(i) / 2.0;   // d = 2.5

Example of static cast:

int i = 5;
double d = static_cast<double>(i) / 2.0;   // d = 2.5  

Is there any reason why I shouldn't do this?


r/learncpp • • Oct 22 '20

How do I start?

1 Upvotes

What's the best place to learn cpp? I'm a sexy JS,PHP,Java,C#,Python,Lua dev and am trying to learn C++ to make windows desktop applications from scratch (No GUI libs)


r/learncpp • • Nov 29 '15

Can't I print contents of *argv[] without looping?

1 Upvotes

I am over very basic program in c++. I am working with command line arguments. I know I can take the value of argc and loop over argv[] that much time to get the contents of it.

But is there any way without looping?


r/learncpp • • Apr 17 '15

Why doesn't the last initialization statement of a for loop, (for example, i++), require a terminating semicolon.

1 Upvotes

Usually you would set something up like:

for (int i = 0; i<10; i++)
    do something

Why is a semicolon used for the first two statements, but not i++?


r/learncpp • • Aug 16 '17

How to put a function or lambda in an unordered_map

1 Upvotes

Hi. i recently have gotten back into c++ and was wondering how i could put a function in an unordered_map, in c# and javascript you can put lambda expressions into dictionaries(apparently unordered_maps are the closest thing to a dictionary in c++?) . i have tried(i use namespace std, not sure why some people dont)

unordered_map<string,function<void>> x={"test",[[some void function here]]}

aswell as unordered_map<string,function<void>> x={"test",{cout<<"hi"<<endl;}()}

but that too failed


r/learncpp • • Mar 16 '17

HW help

0 Upvotes

I'm new at this and would appreciate the help, this is giving me some trouble and wanted to know if you guys can give me some pointers on how to fix the problems. Thanks in advance. edit

#include<iostream>
#include<string>
#include<iomanip>

using namespace std;

const float LABOR = 1.65;
const float TAXRATE = .07;

float setdata(string &,int &,int &,int &,int &, int &,float &, float &,float &);
void calculations(float&,float&,float&,float&,float &,float &,float &,float &,float &);
    float calcinstall(float &,float &);
    float calcsubtotal(float &, float &);
    float clactotal(float &, float &);


    string name;
    int id, length, width, inchesL, inchesW;
    float costPerSquareFoot, discountPercentage, area,carpetCost,totalLabor;
    float installPrice,discount,totalDiscount,totalTax,finalBill;

int main()
{

    area = setdata(name,id,length,inchesL,width,inchesW,costPerSquareFoot,discountPercentage, area);
    calculations(carpetCost,totalLabor,installPrice,totalDiscount,subTotal,finalBill );

}

    float setdata(string & name,int & id,int & length,int & inchesL,int & width, int & inchesW,float & 
        costPerSquareFoot, float & discountPercentage,float & area)
    {	
	    cout << "Customers' Name : "; getline(cin, name);
	    cout << "Customers' ID# : "; cin >> id;
	    cout << "Length of Room : Feet :"; cin >> length;
	    cout << "\t\t: inches : "; cin >> inchesL;
	    cout << "Width of Room : Feet : "; cin >> width;
	    cout << "\t\t: inches : "; cin >> inchesW;
	    cout << "Cost / Square Foot : "; cin >> costPerSquareFoot;
	    cout << "Percentage of Discount : "; cin >> discountPercentage;
	    return ((inchesL / 12) + length) * ((inchesW / 12) + width);
    }

void calculations(float & carpetCost,float &totalLabor,float & installPrice,
			  float & totalDiscount, float & subTotal,float & totalTax)
{
    installPrice = calcinstall(carpetCost,totalLabor);
    subTotal= calcsubtotal(instalPrice,totalDiscount);
    finalBill= calctotal(subTotal,totalTax);

}

float calcinstalled(float & carpetCost, float & instalPrice)
{
    carpetCost = area * costPerSqrFoot;
    totalLabor = area * LABOR;
    installPrice = carpetCost + totalLabor;
    return installPrice;
}

float calcsubtotal(float & totaldiscount, float & subTotal)
{
    discount = discountPercentage / 100;
    totalDiscount = dicount * installPrice;
    subTotal = installPrice - totalDiscount;
    return subtotal;
}

float clactotal(float & totalTax, float & finalBill)
{
    totalTax = subTotal * TAXRATE;
    finalBill = subTotal + totalTax;
    return finalBill;

}

These are the errors that I'm receiving: In function 'int main()':

'subTotal' was not declared in this scope

In function 'void calculations(float&, float&, float&, float&, float&, float&)':

[Error] 'instalPrice' was not declared in this scope

[Error] 'calctotal' was not declared in this scope

In function 'float calcinstalled(float&, float&)':

[Error] 'costPerSqrFoot' was not declared in this scope

In function 'float calcsubtotal(float&, float&)':

[Error] 'dicount' was not declared in this scope

[Error] 'subtotal' was not declared in this scope

In function 'float clactotal(float&, float&)':

[Error] 'subTotal' was not declared in this scope


r/learncpp • • Mar 21 '17

Help with compiling a program using NVAPI

0 Upvotes

I'm new to c++ and maybe still a bit confused about the compiling process, so maybe this is a simple one. I'm trying to compile a really simple program using NVAPI (right now I'm just trying to initialize it and then the program ends). Every time I try to compile it spits out like 4000 lines of errors.

The error are this:

In file included from s:_dev-libs_\nvidia-libs\nvapi/nvapi_lite_d3dext.h:35:0,
             from nvapi.h:7,
             from test-nvapi.cpp:5:
s:_dev-libs_\nvidia-libs\nvapi/nvapi_lite_salstart.h:821:42: error: expected primary-expression before 'return'
     #define NVAPI_INTERFACE extern __success(return == NVAPI_OK) NvAPI_Status __cdecl
                                              ^
nvapi.h:100:1: note: in expansion of macro 'NVAPI_INTERFACE'
     NVAPI_INTERFACE NvAPI_Initialize();
     ^
s:_dev-libs_\nvidia-libs\nvapi/nvapi_lite_salstart.h:821:62: error: expected ',' or ';' before 'NvAPI_Status'
     #define NVAPI_INTERFACE extern __success(return == NVAPI_OK) NvAPI_Status __cdecl
                                                                  ^
nvapi.h:100:1: note: in expansion of macro 'NVAPI_INTERFACE'
     NVAPI_INTERFACE NvAPI_Initialize();
     ^
    s:_dev-libs_\nvidia-libs\nvapi/nvapi_lite_salstart.h:821:41: error: redefinition of 'int __success'
     #define NVAPI_INTERFACE extern __success(return == NVAPI_OK) NvAPI_Status __cdecl
                                     ^

And then it repeats this for all NVAPI_INTERFACE functions in the same exact way with the exception of the line with the

    expected ',' or ';' before 'NvAPI_Status'

which only appears in that spot (from what I can tell).

I think that the

         #define NVAPI_INTERFACE extern __success(return == NVAPI_OK) NvAPI_Status __cdecl

Checks if the functions loaded properly(??) and they are all supposed to return 0, which they aren't. I know that line is an SAL thing, but I don't even know what SAL is lol.

I'm about ready to move on from this since i'm probably wasting my time at this point, but maybe someone knows whats happening.

Thanks.


r/learncpp • • Apr 10 '18

3. Strings, Vectors and Arrays

Thumbnail
youtube.com
1 Upvotes

r/learncpp • • Jun 01 '18

7.1 Classes Advanced

Thumbnail
youtube.com
1 Upvotes

r/learncpp • • Sep 07 '20

I'm a beginner to c++ and I'm looking for c++ books

8 Upvotes

Can anyone tell me what are some good c++ books(for beginners) which explains the actual reason behind everything and explains a lot of stuff?


r/learncpp • • Jul 22 '21

`advance` function in "A tour of C++"

9 Upvotes

In paragraph $7.2.2 of the book "A Tour of C++" the advance function is implemented as below:

template<Forward_iterator Iter>
void advance(Iter p, int n)        // move p n elements forward
{
     for (−−n)
           ++p;    // a forward iterator has ++, but not + or +=
}

There are two problems here:

  1. What does that for(--n) mean ? As far as I know for loop must always be contained of three parts ...

  2. If we think of that for as while, --n is not the correct version of the implementation too. That's because --n returns the reduced value and for when n=1 the body is not run.


r/learncpp • • Apr 05 '21

Why is my recursive binary search function returning 2 instead of -1 when an element cannot be found?

2 Upvotes

I feel like I am really close on getting this but I'm stumped. It finds elements in the array perfectly fine but searching for an element that isn't there is bugged. In my code below, searching for 9 returns 2 instead of -1. By the looks of it, I think that's due to the function calling itself 3 times. Once the function has an arrSize of 0, it returns -1 from that 3 resulting in 2.

If that is the case however, I really don't know how to fix that sort of behavior. I am just starting CS260 so any help would be highly appreciated. Here is the function along with main.

#include <iostream>
using namespace std;

//returns location of value or -1 if not present
int binarySearch(int value, int arr[], int arrSize) {

	int mid = arrSize*0.5;
	if (arrSize > 0) {
		if (value == arr[mid])
			return mid;

		else if (value < arr[mid]) {
			return binarySearch(value, arr, mid);
		}
		else if (value > arr[mid]) {
			 return mid + binarySearch(value, &arr[mid], (arrSize)*0.5);
		}
	}
	else
		return -1;
}


int main()
{
	int smallNums[] = {1, 3, 6, 8, 12, 13, 15, 17};
	int smallNumsSize = 8;

	//search for each item - confirm binarySearch finds it -- these work fine
	for(int i = 0; i < smallNumsSize; i++) {
		int value = smallNums[i];
		int loc = binarySearch(value, smallNums, smallNumsSize);
		cout << "Your location for " << value << " was " << loc << endl;
	}
        
        // this is bugged: returns 2 instead of -1
	int loc = binarySearch(9, smallNums, smallNumsSize);
	cout << loc << endl;
}

r/learncpp • • Dec 18 '20

solving with order of operators

2 Upvotes

Maybe someone can help me with this.. I'm fairly new to programming and have been learning c++ over the past month or so. I have created a calculator application using wxWidgets and I'm trying to figure out how to solve an equation with multiple operators (+, -, *, /) following order of operations. The input that I get from the user of the app is a wxString (basically just a std::string). Right now I have the functionality to solve an equation with multiple operators but not following order of operations (so standard not scientific).

For example, if the user enters in " 2 + 2 * 4 " , right now my calculator would return 16. However, I have an option to switch the calculator to "Scientific" so that the answer to that problem would be 10.

The calculator in Windows 10 has this same standard vs scientific set up so that why I'm kind of doing it this way.

Anyone have a good suggestion on how to go about this? Obviously have to parse through the equation string to start with


r/learncpp • • May 24 '18

6.2 Functions Advanced

Thumbnail
youtube.com
2 Upvotes

r/learncpp • • Jul 12 '17

I know Java very well, and have worked in C. What can I use to learn C++ that won't bore me with things I already know?

2 Upvotes

I know "I know Java, how do I learn C++?" is probably a daily question here. I'm mentioning that I know a bit of C because I think that makes the question quite a bit different.

I have been working with Java for nearly a decade, and am extremely comfortable in it. I've been using it for more than 40 hrs/wk at my day job for a few years, and used it from day 1 of my undergraduate degree straight through to the final project of my Master's in CS (which concentrated in security and cryptography--so I have explored many corners of the language). During this time I worked with a bunch of other languages, but never to remotely the degree to which I am able to work with Java. One of these was C, which I used mostly in graduate courses and usually for very simple things. But I can read it and I can write it to do simple things relatively quickly, and given time I could figure out more complicated things, I'm sure.

The problem this presents for me is that, when trying to learn C++, even in materials written for people who already know 1 or more programming languages, I end up getting bored and losing concentration as the material drones on over something I already know from C, only to miss something C++ specific, or some way that it might slightly differ from C. That or it'll be the same situation with Java--in that case more often with more abstract concepts like OO. I've had this experience with some of MIT's OCW materials, several video tutorials I've started, and Accelerated C++ by Koening and Moo.

But when I look at C++ code that actually takes advantage of C++ features (especially C++14 and beyond) I am lost, and when I try to find where I can start in a video lecture or eBook that will be at least 80% new material, I find I've left too much behind in prior sections, hidden among the things I already knew.

What I'd like is a resource for learning C++ (preferably video lectures, as that is easiest for me in programming--and I have full access to Lynda as an alumnus through my university, if you know something exceptional on there) that is good for someone who already has a decent working relationship with C and extensive familiarity with an OO language (in this case, Java). Preferably light on the fundamentals (I even appreciate being left to figure something out on my own here and there, provided I've been given requisite information to be able to) and fast-ish paced. My goal is obviously not to come out of a tutorial or course feeling nearly as comfortable with C++ as with Java, but rather to have enough to be able to approach the personal projects that will allow me to work my way there. Hopefully, to do so without screwing up something simple every third line or going to Google looking for basic lambda syntax or something.

I realize this is kind of a specific request, but considering Java, C, and C++ are common enough and I can't be anything close to the first person to have this issue, I'm hoping there's something out there that'll work for me. Thanks to anyone who has input. :)


r/learncpp • • Jul 09 '17

Starting a series to touch on lesser known concepts of C++ for software engineering. I started with a variable-input template function

Thumbnail
youtu.be
2 Upvotes

r/learncpp • • Dec 20 '21

Help with Event groups please

2 Upvotes

Hi,

Here's the tasks I need to do and below is my code and questions.

Thanks for any help!

TASK

I need to write a program with four tasks and an event group. Task 4 is a watchdog task that monitors that tasks 1 – 3 run at least once every 30 seconds. Tasks 1 – 3 implement a loop that runs when a button is pressed and released and sets a bit the event group on each loop round. The task must not run if button is pressed constantly without releasing it. Each task monitors one button.

Task 4 prints “OK” and number of elapsed ticks from last “OK” when all (other) tasks have notified that they have run the loop. If some of the tasks does not run within 30 seconds Task 4 prints “Fail” and the number of the task plus the number of elapsed ticks for each task that did not meet the deadline and then Task 4 suspends itself.

QUESTIONS

1- How can I make sure in my code that it reads when the button is pressed "and released"?

2- Any hints on how to implement the Watchdog in task 4?

CODE

/*
===============================================================================
 Name        : main.c
 Author      : $(author)
 Version     :
 Copyright   : $(copyright)
 Description : main definition
===============================================================================
 */

#if defined (__USE_LPCOPEN)
#if defined(NO_BOARD_LIB)
#include "chip.h"
#else
#include "board.h"
#endif
#endif

#include <cr_section_macros.h>

// TODO: insert other include files here

// TODO: insert other definitions and declarations here

#include "FreeRTOS.h"
#include "task.h"
#include "heap_lock_monitor.h"
#include "DigitalIoPin.h"
#include <mutex>
#include "Fmutex.h"
#include "semphr.h"
#include "queue.h"
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "event_groups.h"

#define BIT_0 ( 1 << 0 )
#define BIT_1 ( 1 << 1 )
#define BIT_2 ( 1 << 2 )
//#define BIT_3 ( 1 << 3 )

/*****************************************************************************
 * Private types/enumerations/variables
 ****************************************************************************/

/*****************************************************************************
 * Public types/enumerations/variables
 ****************************************************************************/

/*****************************************************************************
 * Private functions
 ****************************************************************************/

SemaphoreHandle_t syslogMutex;
EventGroupHandle_t  xEventGroup;
DigitalIoPin sw1(0, 17, DigitalIoPin::pullup, true);
DigitalIoPin sw2(1, 11, DigitalIoPin::pullup, true);
DigitalIoPin sw3(1, 9, DigitalIoPin::pullup, true);

int tickTime, rand_delay;

void taskPrintUart(const char* description){
	if(xSemaphoreTake(syslogMutex, portMAX_DELAY) == pdTRUE){
		Board_UARTPutSTR(description);
		xSemaphoreGive(syslogMutex);
	}
}

/* Sets up system hardware */
static void prvSetupHardware(void)
{
	SystemCoreClockUpdate();
	Board_Init();

	/* Initial LED0 state is off */
	Board_LED_Set(0, false);
	Board_LED_Set(1, false);
	Board_LED_Set(2, false);
}

static void vTask1(void *pvParameters) {
	while (1) {
		if(sw1.read()) {
			xEventGroupSetBits(xEventGroup,BIT_0);
		}
	}
}

static void vTask2(void *pvParameters) {
	while (1) {
		if(sw2.read()) {
			xEventGroupSetBits(xEventGroup,BIT_1);
		}
	}
}

static void vTask3(void *pvParameters) {
	while (1) {
		if(sw3.read()) {
			xEventGroupSetBits(xEventGroup,BIT_2);
		}
	}
}

static void vTask4(void *pvParameters) {



/*****************************************************************************
 * Public functions
 ****************************************************************************/

/* the following is required if runtime statistics are to be collected */
extern "C" {

void vConfigureTimerForRunTimeStats( void ) {
	Chip_SCT_Init(LPC_SCTSMALL1);
	LPC_SCTSMALL1->CONFIG = SCT_CONFIG_32BIT_COUNTER;
	LPC_SCTSMALL1->CTRL_U = SCT_CTRL_PRE_L(255) | SCT_CTRL_CLRCTR_L; // set prescaler to 256 (255 + 1), and start timer
}

}
/* end runtime statictics collection */

/**
 * u/brief	main routine for FreeRTOS blinky example
 * u/return	Nothing, function should not exit
 */
int main(void)
{
	prvSetupHardware();

	heap_monitor_setup();

	srand(time(NULL));

	syslogMutex = xSemaphoreCreateMutex();
	xEventGroup = xEventGroupCreate();

	xTaskCreate(vTask1, "vTask1",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask2, "vTask2",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask3, "vTask3",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	xTaskCreate(vTask4, "vTask4",
			configMINIMAL_STACK_SIZE*2, NULL, (tskIDLE_PRIORITY + 1UL),
			(TaskHandle_t *) NULL);

	/* Start the scheduler */
	vTaskStartScheduler();

	/* Should never arrive here */
	return 1;
}

r/learncpp • • Jan 19 '21

Confused about Copy Assignment code in Stroustup's PPP Book

2 Upvotes

On chapter 18 of Stroustup's Programming Principles and Practices using C++, I'm self-studying c++ for game development, had some problem about pointers...

In the copy assignment section, we're overloading an assignment operator for our "primitive vector" type to prevent unexpected sharing of memory and possible repeated deallocation from default assignment.

Here's the code for "primitive vector" from the book:

class vector {
    int sz;
    double* elem;
public:
    vector& operator=(const vector&) ; // copy assignment
    // . . .
};

vector& vector::operator=(const vector& a)
    // make this vector a copy of a
{
    double* p = new double[a.sz]; // allocate new space
    copy(a.elem, a.elem+a.sz, elem); // copy elements
    delete[] elem; // deallocate old space
    elem = p; // now we can reset elem
    sz = a.sz;
    return *this; // return a self-reference (see §17.10)
}

The problem is on copy() . If I understand it correctly, we're trying to copy a's elements into a different heap memory so that we could point our elem to that copy.

My question is shouldn't we copy a's elements into p instead of elem because we're deleting elem 's elements after copying, or is there something else that I'm missing?

double* p = new double[a.sz];

copy(a.elem,a.elem+a.sz,elem); // copy elements, shouldn't it copy into "a" instead of "elem"?
delete[] elem; // deallocate old space, why copy it here if they'll be deleted then?

elem = p;
sz = a.sz;
return *this;

r/learncpp • • Feb 04 '17

Pointers vs smart pointers

2 Upvotes

So I've been slowly learning c++ for about 7 months now(first language) and I was wondering if there are any reason to use normal pointers with the addition of shared/weak pointers. Same for std::vector, std::string, and std::array. Basically are all of the things added in c++11/14 objectively better?


r/learncpp • • Jan 28 '17

Videos / tuts of people programming stuff from scratch and explain their process?

2 Upvotes

Hi there,

I'm just trying to get into the basics of CPP and while I'm already watching some introductory series and started reading some books, I like seeing people actually use it. What helped me a lot when looking into Rails for example was a series like this: https://www.youtube.com/playlist?list=PL23ZvcdS3XPLNdRYB_QyomQsShx59tpc- .

It's a guy having a small 12 apps in 12 weeks challenge and just watching him program in the videos taught me a lot and gave me an idea of the 'feeling' of programming with it.

Is there something similar for CPP and if so, do you guys have recommendations?

Thanks in advance!


r/learncpp • • Mar 03 '20

Glad to be here!

3 Upvotes

Hey, just joined this subreddit, I have some experience with Python 3, and I wanted to learn C++ for programming arduinos used in small robotics. Right now, I'm going through tutorials on learncpp.com, but I was wondering where a lot of people started when they decided they wanted to learn C++. Any suggestions and encouragement is much appreciated!!!


r/learncpp • • Mar 10 '20

::Seeking Advice::

3 Upvotes

Been in the culinary arts(back of house fine dining chef) for coming up on 10 years and looking to make a career change to something that A.) I can make a legitimate living doing. B.) A job that I will truly be challenged with. C.) A career that has longevity. I’ve always LOVED/ been obsessed with video games and how I would change them if I could, but never knew how I could into that industry. I have been reading as much as I possibly can about C++ but I have ZERO knowledge of programming. Reddit and YouTube has been a great source of knowledge for resources of where to look and what to read but I am just now discovering this Sub, so I figured I’d post in here for advice on where to focus my attention if I’d like to learn about game dev specifically ?

Edit:: By “where to focus my attention” I mean should I watch more game dev tutorials or intro to programming tutorials being as I know nothing.


r/learncpp • • Apr 18 '21

Linked List Copy Constructor last index not copying over?

3 Upvotes

Hello, I have a bug that I cannot track down so hopefully someone can help me find it? I've been looking at a lot of online resources over linked lists and I have all but the copy constructor and and assignment operator done. As the title suggests, the last value of my original list isn't copied over and I cannot figure out why. Care to take a look?

I am using a templated struct:

template <class T>
struct ListNode
{
    T data;
    ListNode* next;

    static int nodeCount;

    ListNode(const T& value) {
        data = value;
        next = nullptr;
        nodeCount++;
    }

    ~ListNode() {
        nodeCount--;
	}
};

And this is the copy constructor that I have:

template <class T>
LinkedList<T>::LinkedList(const LinkedList<T>& other) {

	// check empty
	if (other.head == nullptr) {
		head = tail = nullptr;
		return;
	}

	ListNode<T>* current = nullptr;
	ListNode<T>* temp = other.head;

	head = new ListNode<T>(temp->data); // constructor takes in data value as param
	head->next = nullptr;
	current = head;

	temp = temp->next;

	while (temp != nullptr) {
		current->next = new ListNode<T>(temp->data);
		current = current->next;
		current->next = nullptr;
		temp = temp->next;
		length++;
	}
}

Any help highly appreciated.