invalid pointer when using strings for generic class - c++

So this is for my data structures class and I am struggling to understand why I am getting the error: invalid pointer: 0x00000000023ce048 ***. It only happens when I define my generic class using strings: NSequence<string> v3(10);
It should be noted that using int or even a different class worked fine. However, as soon as I write the line: NSequence<string> v3(10); I get the pointer error and I have no idea why?
UPDATE:
I've found that it was actually my destructor class that was causing the error. However, I now have no idea why this would cause an error specifically with string?
template<typename T>
NSequence<T>::~NSequence()
{
delete items;
}
Here is the definition of my class:
#include <algorithm>
#include <iostream>
#include <utility>
/* XXX: Implement all member functions for NSequence in NSequence.hpp */
template <typename T>
class NSequence
{
public:
explicit NSequence( int initSize = 0 );
private:
int numOfItems;
int totalCapacity;
T * items;
};
#include "NSequence.hpp" // do not change this line
#endif
Here is my constructor function:
template<typename T>
NSequence<T>::NSequence(int initSize)
{
if(initSize==0)
initSize=1;
numOfItems = initSize;
totalCapacity = initSize;
items = new T[totalCapacity];
}
Any advice would be greatly appreciated!

Related

How to implement constructors of Class A that has a member variable vector <Class B>,which is its Base function, using initializer_list and template?

So the problems are:
Class Stan must have a constructor that enables it to recieve and store unlimited nubmer of elements and it has to be implemented using templates. Also, demonstrate it in the main function
Class Stan must have a constructor that enables it to recieve and store unlimited nubmer of elements and it has to be implemented using initializer lists. Also, demonstrate in main function
Place class Stan into the namespace Zgrada
Lets assume that there are 2 types of Stans - Apa & Gar. Within the main function it is necessary to demonstrate polimorphism by implementing getVrsta(); which returns one of the 2 types
I have no clue how to do more than this.
Thanks for the help!
#include <string>
#include <vector>
#include <functional>
#include <algorithm>
#include <iterator>
using namespace std;
int Element::brV = 0;
class Element {
public:
string naziv;
double obujam;
static int brV;
Element(string n, double o) : naziv(n), obujam(o) {
if (o > 3.) brV++;
}
int getVelikiElementi(){
return brV;
}
void virtual GetVrsta(){
cout << "Vrsta Stana: ";
}
};
template <class T> //I think i got the templates_init right
class Stan : public Element {
public:
vector<Element> Elementi;
template<class...T>
Stan(T...arg) : Elementi({arg...}){}
Stan(initializer_list<Elementi>) : Element (){} // But this most certainly not
void GetVrsta(){
}
};
int main () {
Element X("a", 3.);
Element Y("b", 2.);
Element Z("c", 1.);
vector <Element*> E={X,Y,Z}; // initilizer_lista_const_call
return 0;
}```

How can I get rid of the <error-type> type that is appearing in my method template? Both the input to the method and the class are templates

I am getting the error
declaration is incompatible with "void spectrogram<T>::update(<error-type> x)
I don't see any difference between the declaration and the definition of the method, not sure why it is complaining about just this one definition and not the constructor or destructor.
Here is vComplex.hpp
#ifndef VCOMPLEX_H
#define VCOMPLEX_H
template <class T>
class vComplex {
public:
T* realp;
T* imagp;
int length; // for bookkeeping
vComplex(void) { }
vComplex (T* I, T* Q, int len) {
realp = I;
imagp = Q;
length = len;
}
~vComplex(void) {
free(realp);
free(imagp);
}
void put(T* I, T*Q, int len) {
realp = I;
imagp = Q;
length = len;
}
};
#endif
the function declaration for update in spectrogram.hpp, with other members removed:
#ifndef SPECTROGRAM_H
#define SPECTROGRAM_H
template <typename T>
class spectrogram {
public:
void update(vComplex<T> x);
};
#endif
and the function signature (and includes) for update in spectrogram.cpp:
#include <stdio.h>
#include <math.h>
#include "spectrogram.hpp"
#include "vComplex.hpp"
template <typename T>
void spectrogram<T>::update(vComplex<T> x) {
//do stuff
}
In VS 2017, I get the red underline under update and everything inside of it breaks basically. VS is saying T is undefined which I'm assuming is caused by the overall error. I have to use dynamically allocated pointers, I don't have the option of using other types or containers.

why i get {error :2061 identifier {ctor

In header file:
#ifndef Array_h
#define Array_h
#include "stdafx.h"
using namespace std;
template<class T>
class Arrayc
{
private:
int Arraysize;
int length;
T *array;
public:
Arrayc(int size);
~Arrayc();
};
template<class T>
Arrayc<T>::Arrayc(int size)
{
Arraysize = size;
length = 0;
array = new T[Arraysize];
}
#endif
In main source file:
Arrayc<int> *Arrayofintegers;
Arrayc<float> *Arrayoffloat;
// These lines have the error
Arrayofintegers = new Arrayc<int>::Arrayc(10);
Arrayoffloat = new Arrayc<float>::Arrayc(5);
You only need specify the scoped name, Arrayc<T>::Arrayc, when defining the constructor.
To call the constructor, simply use Arrayc<T>(/*args*/).
Of course, you really don't even need new at all, but that's unrelated to the error.
You are not passing any clues to your constructors of what you want T to be at the time that you use them. I'd suggest adding a parameter T to your constructor, even if you only use it as a phony initializer value, so that the compiler can deduce what type Arrayc() will be, e.g., new Arrayc(10, 0) or new Arrayc (10, 0.0f)

No Matching Function Call

I'm new to C++ and trying to code a HashTable data structure.
I've written it to be generic using templates, and I've included a HashEntry object to use in it to allow for easy quadratic probing for collisions.
The code I have is:
(in a .C file that #include's the below class definition .H file):
HashEntry::HashEntry()
{
this->isActive = false;
}
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
using namespace std;
#define Default_Size 50000
class HashEntry;
template <class T> class HashTable
{
private:
int size;
int occupied;
T array[Default_Size];
public:
HashTable();
int Size();
void Add(T t);
void DebugAdd(T t, int index);
T* Get(string index);
/* How do I declare the existence of HashEntry BEFORE here? */
int FindNextOpen(HashEntry he); // Only works for hash_entry objects!
int Hash(string str);
void Rehash();
};
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry();
HashEntry(Entry e);
bool IsActive();
Entry GetEntry();
};
Whenever I try and compile everything, I get the error for the HashEntry constructor above:
"no matching function for call to Entry::Entry()" ... "candidates are.....".
I have no idea what it means -- when I try to include a default Entry() constructor (my first interpretation), it throws more errors.
Thanks for the help!
UPDATE -- ENTRY.C:
#include "Entry.H"
/* ***Entry Methods*** */
/*
* Overloaded Entry obejct constructor that provides a string value.
*/
Entry::Entry(string s)
{
this->value = s;
this->count = 0;
}
/*
* Returns the number of times this Entry has been accessed/
* found.
*/
int Entry::Count()
{ return this->count; }
/*
* Returns the string value stored in the Entry object.
*/
string Entry::Value()
{ return this->value; }
And the associated .H file with the class definitions is:
#include <iostream>
#include <string>
#include "Entry.C"
Whoa! Never, ever #include a source file in a header.
Your Entry.C should not exist. Instead define the constructor in your header, inside the class definition:
class HashEntry
{
private:
Entry e;
bool isActive;
public:
HashEntry() : isActive(true) {}
...
}
One thing that you haven't shown us is the definition of the class Entry. That is one of the sources of your problem. It's a bit hard to pin down your problem when you didn't show us the very thing that is causing it.
I found the problem.
The error message says there is not matching function call for "Entry::Entry()". Because in no case was I actually creating Entry objects I had no idea what it meant.
I tried adding an explicit default constructor for class Entry and it resolved.
Thanks for the help everyone!

"undefined reference" to a template class function

I am writing a template class for an array of objects, call it arrayobjclass, which holds pointers to other objects, specifically to other arrays in my implementation. The arrays are implemented as objects as well, call them arrayclass.
Looking for compilation ready with minimal changes.
when I try to test my classes with the following line,
g++ main.cpp arrayclass.cpp arrayobjclass.cpp -o arrayobj
I get the following error:
/tmp/ccEpROXj.o(.text+0x17c): In function `main':
: undefined reference to `arrayobjclass<arrayclass, int>::arrayobjclass(int)'
/tmp/ccEpROXj.o(.text+0x1dc): In function `main':
: undefined reference to `arrayobjclass<arrayclass, int>::addelem(arrayclass*)'
collect2: ld returned 1 exit status
I really can't understand what is wrong. any help would be appreciated. the short relevant part of the code is below if it helps. THANKS IN ADVANCE!
This is what i have in main:
#include "arrayclass.h"
#include "arrayobjclass.h"
#include <iostream>
// 5 arrays of 10 maxsize each
#define MAXSIZE_array 10
#define NUMB_objs 5
using namespace std;
int main () {
//create a simple array as an arrayclass object
arrayclass * numbers1 = new arrayclass (MAXSIZE_array);
//array of objects to hold pointers to simple arrays as created above
arrayobjclass<arrayclass,int> * myobjs = new arrayobjclass<arrayclass,int> (NUMB_objs);
//fill up the simple array
int i;
for (i=0; i<10; i++) {
numbers1->addelem(i);
}
//add a pointer to the simple array in my array of objects
myobjs->addelem(numbers1);
}
//arrayobjclass.h
//declarations of an array of pointers to objects
template <class obj, class key>
class arrayobjclass {
private:
//obj * arrayptr;
obj * objarray [];
int maxsize;
int totalelem;
public:
arrayobjclass(int);
bool addelem(obj *);
};
//arrayobjclass.cpp
//implementation of arrayobjclass, array of pointers to objects
#include "arrayobjclass.h"
#include "arrayclass.h"
template <class obj,class key>
arrayobjclass<obj,key>::arrayobjclass (int size){
maxsize=size;
objarray = new obj[maxsize];
totalelem = 0;
}
template <class obj, class key>
bool arrayobjclass<obj,key>::addelem (obj * newobj) {
if (totalelem < maxsize ) {
objarray[totalelem] = newobj;
totalelem ++;
return true;
}
return false;
}
//arrayclass.h
class arrayclass {
private:
int * arrayptr;
int maxsize;
int totalelem;
public:
arrayclass(int);
bool addelem(int);
};
//arrayclass.cpp
#include "arrayclass.h"
arrayclass::arrayclass (int size){
maxsize=size;
arrayptr = new int[maxsize];
totalelem = 0;
}
bool arrayclass::addelem (int addval) {
if (totalelem < maxsize ) {
arrayptr[totalelem] = addval;
totalelem ++;
return true;
}
return false;
}
You can't put template declarations in .cpp files like that. Template declarations and implementation need to be visible in the same translation unit. Put template implementations in headers that you #include directly.
Define your function templates in the header. Compiler needs to see them.
Cheers & hth.,
Because templates are compiled when required, this forces a
restriction for multi-file projects: the implementation (definition)
of a template class or function must be in the same file as its
declaration. That means that we cannot separate the interface in a
separate header file, and that we must include both interface and
implementation in any file that uses the templates.
From http://www.cplusplus.com/doc/tutorial/templates/
For anyone passing by
you can also #include the implementation files in main
in main:
#include "arrayobjclass.h"
#include "arrayclass.h"
#include "arrayobjclass.cpp"
#include "arrayclass.cpp"