Something weird with operator overloading (C++) - c++

###MyClass.h###
#ifndef _MyClass
#define _MyClass
#include <string>
using namespace std;
class MyClass
{
public:
MyClass(const string name, const string text);
void display(ostream & out) const;
MyClass & operator = (const MyClass & m);
int compare(const MyClass & right) const;
private:
string _name;
string _text;
};
bool operator < (const MyClass & left, const MyClass & right);
ostream & operator << (ostream & out, const MyClass & mc);
#endif
###Node.h###
#include <string>
#include "MyClass.h"
using namespace std;
typedef MyClass * DataType;
class Node
{
private:
DataType item; // data
Node * lchild; // left child pointer
Node * rchild; // right child pointer
public:
Node(DataType Item);
DataType getItem() const;
void setItem(const DataType & data);
Node* getLChild() const;
void setLChild(Node * p);
Node* getRChild() const;
void setRChild(Node * p);
virtual ~Node();
};
###BST.h###
#include "Node.h"
using namespace std;
class BST
{
private:
Node * root;
bool Search(const DataType item, Node * r) const;
void Insert (DataType item, Node * ptr);
void Destructor(const Node * r);
public:
BST();
bool IsEmpty() const;
void Insert(const DataType item);
bool Search(const DataType item) const;
virtual ~BST();
};
###MyClass.cpp###
#include <iostream>
#include "MyClass.h"
using namespace std;
MyClass::MyClass(const string name, const string text)
{
_name = name;
_text = text;
}
void MyClass::display(ostream & out) const
{
out << "Name: " << _name << endl;
out << "Text: " << _text << endl;
}
MyClass & MyClass::operator = (const MyClass & m)
{
if (this == & m)
return *this;
_name = m._name;
_text = m._text;
return *this;
}
int MyClass::compare(const MyClass & right) const
{
return _name.compare(right._name);
}
bool operator < (const MyClass & left, const MyClass & right)
{
return left.compare(right) > 0;
}
ostream & operator << (ostream & out, const MyClass & mc)
{
mc.display(out);
return out;
}
###Node.cpp###
#include "Node.h"
Node::Node(DataType Item):item(Item)
{
lchild = 0;
rchild = 0;
}
DataType Node::getItem() const
{
DataType anItem = item;
return anItem;
}
void Node::setItem( const DataType & data)
{
item = data;
}
Node* Node::getLChild() const
{
Node * p = lchild;
return p;
}
void Node::setLChild(Node * p)
{
lchild = p;
}
Node* Node::getRChild() const
{
Node * p = rchild;
return p;
}
void Node::setRChild(Node * p)
{
rchild = p;
}
Node::~Node()
{
}
###BST.cpp###
#include <iostream>
#include "BST.h"
using namespace std;
bool BST::Search(const DataType item) const
{
return Search(item, root);
}
bool BST::Search(const DataType item, Node * r) const
{
if(r != 0)
{
if (item == r->getItem())
return true;
else
{
if (item < r->getItem())
return Search(item, r->getLChild());
else
return Search(item, r->getRChild());
}
}
else
return false;
}
BST::BST()
{
root = 0;
}
bool BST::IsEmpty() const
{
return (root == 0);
}
void BST::Insert(const DataType item)
{
if(root == 0)
root = new Node(item);
else
Insert(item, root);
}
void BST::Insert(DataType item, Node * ptr)
{
if (item < ptr->getItem())
{
if (ptr->getLChild() == 0)
ptr->setLChild(new Node(item));
else
Insert(item, ptr->getLChild());
}
else
{
if (ptr->getRChild() == 0)
ptr->setRChild(new Node(item));
else
Insert(item, ptr->getRChild());
}
}
void BST::Destructor(const Node * r)
{
if(r!=0)
{
Destructor( r->getLChild());
Destructor( r->getRChild());
delete r;
}
}
BST::~BST()
{
Destructor(root);
}
###main.cpp###
#include <iostream>
#include "MyClass.h"
#include "BST.h"
using namespace std;
void main()
{
MyClass * mc1 = new MyClass("Tree","This is a tree");
MyClass * mc2 = new MyClass("Book","This is a book");
MyClass * mc3 = new MyClass("Zoo","This is a zoo");
BST * tree = new BST();
tree->Insert(mc1);
tree->Insert(mc2);
tree->Insert(mc3);
cout << boolalpha << ("Book" < "Tree") << endl;
cout << (mc2 < mc1) << endl;
cout << (tree->Search(new MyClass("Book",""))) << endl;
}
Result is true false false
I don't know what's wrong with my operator overloading? (mc2 should
less than mc1)
I'm not sure if this is correct for searching a "MyClass" node in a BST?
and the result is "not found"....I traced it into "BST.cpp",
and found that the problem also occurs at " if (item < r->getItem()) "
Can anyone help me or give me a hint....thank you so much!

Here you are just comparing pointers, i.e memory addresses:
cout << (mc2 < mc1) << endl;
To compare the objects, you need to dereference the pointers:
cout << ((*mc2) < (*mc1)) << endl;
In your code snippet, there is no reason for mc1, mc2, etc. to be pointers, so you could avoid the problem by creating objects on the stack directly:
MyClass mc1("Tree","This is a tree");
and so on. I would even go further and say that you should only dynamically allocate objects with new if you really are sure you need to and have good reasons not to allocate automatically on the stack. And if you really must use dynamically allocated pointers, have a look at C++ smart pointers.

Related

C++: Why Position constructor are called when the argument type does not match?

This will be a bit lengthy but anyhow i tried my best to simplify it using code.
I am building a binary tree but noticed something peculiar.
linked_binary_tree.h
#ifndef LINKED_BINARY_TREE_H
#define LINKED_BINARY_TREE_H
#include <iostream>
#include <list>
using namespace std;
typedef int Elem;
class LinkedBinaryTree {
protected:
struct Node {
Elem ele;
Node *par;
Node *left;
Node *right;
Node(): ele(), par(NULL), left(NULL), right(NULL) {}
};
public:
class Position {
friend LinkedBinaryTree;
private:
Node *v;
public:
Position(Node *_v=NULL): v(_v) { cout << "Position constr" << endl;}
Elem &operator*() const {
return v->ele;
}
Position left() const {
return Position (v->left);
}
Position right() const {
return Position (v->right);
}
Position parent() const {
return Position(v->par);
}
bool isRoot() const {
return v->par==NULL;
}
bool isExternal() const {
return v->left==NULL && v->right==NULL;
}
};
typedef list<Position> PositionList;
LinkedBinaryTree();
int size() const;
bool empty() const;
Position root() const;
PositionList positions(int trv) const;
void addRoot();
void expandExternal(const Position &p);
Position removeAboveExternal(const Position &p);
protected:
void preorder(Node *v, PositionList &pl) const;
void postorder(Node *v, PositionList &pl) const;
void inorder(Node *v, PositionList &pl) const;
private:
Node * _root;
int n;
};
#endif
linked_binary_tree.cc
#include <iostream>
#include <list>
#include "linked_binary_tree.h"
using namespace std;
LinkedBinaryTree::LinkedBinaryTree(): _root(NULL), n(0) {}
int LinkedBinaryTree::size() const {
return n;
}
bool LinkedBinaryTree::empty() const {
return size()==0;
}
LinkedBinaryTree::Position LinkedBinaryTree::root() const {
cout << "LinkedBinaryTree::root()" << endl;
return Position(_root);
}
void LinkedBinaryTree::addRoot() {
_root=new Node;
n=1;
_root->ele=n;
}
void LinkedBinaryTree::expandExternal(const Position &p) {
Node *v = p.v;
v->left=new Node;
v->left->par=v;
v->left->ele=++n;
v->right=new Node;
v->right->par=v;
v->right->ele=++n;
}
LinkedBinaryTree::PositionList LinkedBinaryTree::positions(int trv) const {
PositionList pl;
if (trv==1)
preorder(_root,pl);
else if (trv==2)
inorder(_root,pl);
else postorder(_root,pl);
return PositionList(pl);
}
void LinkedBinaryTree::preorder(Node *v, PositionList &pl) const {
pl.push_back(Position(v));
if (v->left!=NULL)
preorder(v->left,pl);
if (v->right!=NULL)
preorder(v->right,pl);
}
void LinkedBinaryTree::postorder(Node *v, PositionList &pl) const {
if (v->left!=NULL)
preorder(v->left,pl);
if (v->right!=NULL)
preorder(v->right,pl);
pl.push_back(Position(v));
}
void LinkedBinaryTree::inorder(Node *v, PositionList &pl) const {
if (v->left!=NULL)
preorder(v->left,pl);
pl.push_back(Position(v));
if (v->right!=NULL)
preorder(v->right,pl);
}
linked_binary_tree_main.cc
#include <iostream>
#include "linked_binary_tree.h"
using namespace std;
int main() {
LinkedBinaryTree lbt;
lbt.addRoot();
cout << "post addRoot()" << endl;
LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root()); // --> STATEMENT 1
cout << "post lbt.root()" << endl;
//LinkedBinaryTree::Position pr = lbt.root(); // --> STATEMENT 2
lbt.expandExternal(pr);
cout << "LinkedBinaryTree.size() :- " << lbt.size() << endl;
// 1-preorder 2-inorder 3-postorder
auto iter=lbt.positions(3);
auto cbeg=iter.cbegin();
auto cend=iter.cend();
for (; cbeg!=cend; cbeg++) {
cout << cbeg->operator*() << " ";
}
cout << endl;
return 0;
}
Results executing linked_binary_tree_main
post addRoot()
LinkedBinaryTree::root() --> STATEMENT 3
Position constr --> STATEMENT 4
post lbt.root()
LinkedBinaryTree.size() :- 3
Position constr
Position constr
Position constr
2 3 1
Note:
Statement 1
LinkedBinaryTree::Position pr = LinkedBinaryTree::Position(lbt.root()); // --> STATEMENT 1
a. The lbt.root() actually returned LinkedBinaryTree::Position instance.
b. There is no LinkedBinaryTree::Position constructor which takes in a Position instance. Instead it has the following:
Position(Node *_v=NULL): v(_v) { cout << "Position constr" << endl;}
which is it takes a pointer to a Node argument. Yet STATEMENT 1 works showing that LinkedBinaryTree::Position(Node *v) constructor is called.
c. If you comment out STATEMENT 1 and use STATEMENT 2 that of course would work as well.
So why does STATEMENT 1 works?
Appreciate any insight.
Thanks.
The constructor you're seeing is not the one you think it is.
The constructor in STATEMENT 1 is the (compiler-generated) copy-constructor.
The constructor printing the output Position constr happens in the LinkedBinaryTree::root function:
return Position(_root);
This was much easier to see once I created a more minimal example (together with some extra output).

BST inorder method referencing vector showing error: declaration is incompatible

I am a beginner at c++ and I am coding a program that stores data into a BST template class the being another class called log_t that stores the variables, I am trying to use the inorder method from the BST class to reference a vector from main, to input the values into and be able to use it in the main class
my main class
int main(int argc, char* argv[])
{
BST<log_t> l;
string infilename = "";
string filePath = "data\\";
string files[1] = {
filePath + "MetData-31-3a.csv"
//filePath + "Jan20071toDec31abcdefghijklmnopq",
//filePath + "Jan20081toDec31abcdefghijklmnopq",
//filePath + "MetData_Jan01-2010-Jan01-2011-ALL"
};
/// checks if file can open
for (int i = 0; i < 1; i++) {
infilename = files[i];
ifstream infile(infilename);
if (!infile.is_open())
{
cout << "unable to read file" << files[i] << endl;
}
else
{
cout << "reading file" << files[i] << endl;
}
/* parse sensor data csv file */
string tmp;
getline(infile, tmp); // skip the first line
while (getline(infile, tmp))
{
// if successfully parsed then append into vector
log_t logline;
if (ParseLog(tmp, logline))
l.insert(logline);
}
}
cout << " end with reading file" << endl;
/* aggregate/filter logs */
Vector<log_t> vec;
l.inorder(vec);
/* prompt menu */
// this array stores all the menu option callback functions
void(*funs[])(const Vector<log_t> & vec) = { NULL, &option1, &option2, &option3, &option4, &option5,&option6 };
// keep printing menu in loop
while (true)
{
// prompt menu and ask user to select option
int choice = PromptMenu();
// check validity of choice
if (choice < 1 || choice > 6)
{
cout << "invalid choice" << endl;
}
else
{
cout << endl;
// call menu option handler
(funs[choice])(vec);
}
}
system("pause");
return -1;
}
my BST class
#include <string>
#include <iostream>
#include <stream>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "log_t.h"
#include "Vector.h"
using namespace std;
template <class T>
class BST {
private:
struct Node {
T num;
Node* left;
Node* right;
};
Node* root = NULL;
Node* insert(Node* node, T x);
Node* newnode(T num);
void removeprivate(T num, Node* parent);
T findsmallestprivate(Node* ptr);
void inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const& log);
void postorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
void preorderprivate(Node* ptr, void (BST<T>::* FT)(T&));
//void inorderprivate(Node* ptr);
//void postorderprivate(Node* ptr);
//void preorderprivate(Node* ptr);
void removematch(Node* parent, Node* match, bool left);
public:
void insert(T num);
void remove(T num);
void removerootmatch();
T findsmallest();
void inorder(Vector<log_t>const& log);
void postorder();
void preorder();
void print(T& p) { cout << p << " "; };
};
template <class T>
void BST<T>::inorder(Vector<log_t>const& log) {
inorderprivate(root,print,log);
}
template <class T>
void BST<T>::inorderprivate(Node* ptr, void (BST<T>::* FT)(T&), Vector<log_t>const&
log) {
if (root != NULL)
{
if (ptr->left != NULL)
{
inorderprivate(ptr->left, FT);
}
(this->*FT)(log);
log.Append( ptr->num);
if (ptr->right != NULL)
{
inorderprivate(ptr->right, FT);
}
}
else
{
cout << "tree is empty";
}
}
my log_t class the T type
#pragma once
#ifndef LOG_T_H
#define LOG_T_H
#include <iostream>
#include <stream>
#include <string>
#include <algorithm>
#include <iomanip>
#include <stream>
#include "date.h"
#include "times.h"
#include "BST.h"
class log_t
{
public:
log_t();
log_t(log_t& log);
float gettemp();
float getwind();
float getsolar();
void setwind(float wind);
void setsolar(float rad);
void settemp(float temp);
Date date;
Times time;
private:
float wind_speed;
float solar_radiation;
float air_temperature;
};
log_t::log_t()
{
wind_speed = 0;
solar_radiation = 0;
air_temperature = 0;
}
log_t::log_t(log_t& log) {
wind_speed = log.wind_speed;
solar_radiation = log.solar_radiation;
air_temperature = log.air_temperature;
date.SetDate(log.date.GetDay(), log.date.GetMonth(), log.date.GetYear());
time.SetHour(log.time.GetHour());
time.SetMinute(log.time.GetMinute());
}
float log_t:: gettemp()
{
return air_temperature;
}
float log_t::getwind() {
return wind_speed;
}
float log_t::getsolar() {
return solar_radiation;
}
void log_t::setwind(float wind)
{
wind_speed = wind;
}
void log_t::setsolar(float rad)
{
solar_radiation = rad;
}
void log_t::settemp(float temp)
{
air_temperature = temp;
}
#endif // LOG_T_H
my vector class
#pragma once
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
#include <stream>
#include <string>
template <class T>
class Vector
{
public:
Vector();
Vector(int capacity);
Vector(const Vector& vec);
Vector& operator=(const Vector& vec);
~Vector();
int GetSize() const;
void Expand();
T& GetLast();
void Append(const T& val);
T& operator[](int idx);
const T& operator[](int idx) const;
private:
T* elems;
int capacity;/** < int capacity, stores the size of the array */
int count;
void CopyFrom(const Vector& vec);
};
template <class T>
inline Vector<T>::Vector() : elems(nullptr), capacity(0), count(0)
{
}
template <class T>
inline Vector<T>::Vector(int capacity)
: elems(new T[capacity]()), capacity(capacity), count(0)
{
}
template <class T>
inline Vector<T>::Vector(const Vector& vec)
{
CopyFrom(vec);
}
template <class T>
inline Vector<T>& Vector<T>::operator=(const Vector& vec)
{
if (elems)
delete[] elems;
CopyFrom(vec);
return *this;
}
template <class T>
inline Vector<T>::~Vector()
{
if (elems)
delete[] elems;
}
template <class T>
inline int Vector<T>::GetSize() const
{
return count;
}
template <class T>
inline void Vector<T>::Expand()
{
++count;
if (count > capacity)
if (capacity)
capacity *= 2;
else
capacity = 4;
T* tmp = new T[capacity]();
for (int i = 0; i < count - 1; ++i)
tmp[i] = elems[I];
if (elems)
delete[] elems;
elems = tmp;
}
template <class T>
inline T& Vector<T>::GetLast()
{
return elems[count - 1];
}
template <class T>
inline void Vector<T>::Append(const T& oval)
{
Expand();
GetLast() = val;
}
template <class T>
inline T& Vector<T>::operator[](int idx)
{
return elems[idx];
}
template <class T>
inline const T& Vector<T>::operator[](int idx) const
{
return elems[idx];
}
template <class T>
inline void Vector<T>::CopyFrom(const Vector& vec)
{
elems = new T[vec.capacity]();
capacity = vec.capacity;
count = vec.count;
for (int i = 0; i < count; ++i)
elems[i] = vec.elems[i];
}
#endif //VECTOR_H
the errors that keep showing up are
Severity Code Description Project File Line Suppression State
Error (active) E0147 declaration is incompatible with "void BST::inorder(const Vector<> &log)" (declared at line 241 of "C:\Users\Frances\Documents\A2\A2\BST.h") A2 C:\Users\Frances\Documents\A2\A2\BST.h 241
Severity Code Description Project File Line Suppression State
Error C2065 'log_t': undeclared identifier A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
Severity Code Description Project File Line Suppression State
Error C2923 'Vector': 'log_t' is not a valid template type argument for parameter 'T' A2 C:\Users\Frances\Documents\A2\A2\BST.h 33
could someone help me figure out what it is that's causing this or what I am doing wrong, I have been trying to find an answer for hours and haven't been successful thank you

Writing templete class Liste get problems

My teacher asked to write a templete class List(just like in the STL)
My code compile but it will crash but I CAN`T find why, can anyone try to help me?
I think maybe there is problem with the constructor with two parameters?
-----Main.cpp------
#include "Liste.h"
#include <iostream>
int main()
{
Liste<int> l ;
int x = 5 ;
int y = 6 ;
int z = 7 ;
l.insert_first(y) ;
l.insert_first(x) ;
l.insert_last(z) ;
std::cout << l << std::endl ;
}
-----Liste.h------
#pragma once
#include <stdio.h>
#include <iostream>
#include "NoeudListe.h"
template <class T> class Liste
{
private:
NoeudListe<T>* tete;
NoeudListe<T>* fin;
public:
Liste()
{
tete = new NoeudListe<T>(NULL,fin,NULL); //<-----I think the problem lies here beacause the val can`t be NULL? But I tried 0, still not work...
fin = new NoeudListe<T>(tete,NULL,NULL);
}
void insert_after (T& val, NoeudListe<T>* location)
{
NoeudListe<T>* local = new NoeudListe<T>(location,location->getNext(),val);
(*(location->getNext())).setPrev(local);
location->setNext(local);
}
void insert_first(T& val)
{
insert_after (val, tete);
}
void insert_last(T& val)
{
insert_after (val, fin->getPrev());
}
friend std::ostream& operator << (std::ostream& os,const Liste<T>& location)
{
NoeudListe<T>* local=(location.tete)->getNext();
while( local->getVal() != NULL )
{
os<< local->getVal() << "\n";
local=local->getNext();
}
return os;
}
};
-----NoeudListe.h------
#pragma once
template <class T> class NoeudListe
{
private:
NoeudListe* prev;
NoeudListe* next;
T val;
public:
NoeudListe(NoeudListe* p, NoeudListe* n, const T& v)
{
prev = p;
next = n;
val = v;
}
void setNext(NoeudListe* n){ next = n;}
void setPrev(NoeudListe* p){ prev = p;}
void setVal(const T& v){ val = v;}
NoeudListe* getNext(){ return next;}
NoeudListe* getPrev(){ return prev;}
T getVal(){ return val;}
};
friend std::ostream& operator << (std::ostream& os,const Liste<T>& location)
{
NoeudListe<T>* local=(location.tete)->getNext();
while( local->getVal() != NULL )
{
os<< local->getVal() << "\n";
local=local->getNext();
}
return os;
}
You don't test here if local is NULL (why are you testing if local->getVal() is NULL ?), so you will get a segfault here.

glibc detected *** ./a.out: munmap_chunk(): invalid pointer:

There are many questions like this but after looking at some cases, I guess this question is case-specific so I post my code and pointed out where the problem takes place may you be patient reading my code?
uniBTree.h
#ifndef uniBTree_H
#define uniBTree_H
#include "uniTreeNode.h"
#include <cassert>
template<class T>
class uniBTree {
private:
uniTreeNode<T> *root;
int delete_helper(uniTreeNode<T> *);
uniTreeNode<T> *insert_helper(uniTreeNode<T> *, const T);
void in_print_helper(const uniTreeNode<T> *) const;
void pre_print_helper(const uniTreeNode<T> *) const;
void post_print_helper(const uniTreeNode<T> *) const;
public:
uniBTree(void);
uniBTree(uniTreeNode<T> *r);
~uniBTree(void);
void insert(const T i);
void in_print(void) const;
void pre_print(void) const;
void post_print(void) const;
};
template<class T>
uniBTree<T>::uniBTree(void)
{
root = NULL;
}
template<class T>
uniBTree<T>::uniBTree(uniTreeNode<T> *r)
{
root = r;
}
template<class T>
int uniBTree<T>::delete_helper(uniTreeNode<T> *n)
{
int count = 0;
if (n == NULL)
return 0;
count += delete_helper(n->get_left());
count += delete_helper(n->get_right());
delete n;
count++;
return count;
}
template<class T>
uniBTree<T>::~uniBTree(void)
{
int count = delete_helper(root);
std::cout << "uniBTree<T>::~uniBTree<T>(void)\n";
std::cout << count << " nodes deleted\n";
}
template<class T>
void uniBTree<T>::in_print() const
{
in_print_helper(root);
}
template<class T>
void uniBTree<T>::pre_print() const
{
pre_print_helper(root);
}
template<class T>
void uniBTree<T>::post_print() const
{
post_print_helper(root);
}
template<class T>
void uniBTree<T>::in_print_helper(const uniTreeNode<T> *current) const
{
if (current == NULL)
return;
in_print_helper(current->get_left());
current->print();
in_print_helper(current->get_right());
}
template<class T>
void uniBTree<T>::pre_print_helper(const uniTreeNode<T> *current) const
{
if (current == NULL)
return;
current->print();
pre_print_helper(current->get_left());
pre_print_helper(current->get_right());
}
template<class T>
void uniBTree<T>::post_print_helper(const uniTreeNode<T> *current) const
{
if (current == NULL)
return;
post_print_helper(current->get_left());
post_print_helper(current->get_right());
current->print();
}
template<class T>
void uniBTree<T>::insert(const T i)
{
if (root == NULL)
root = new uniTreeNode<T>(i, NULL, NULL);
else
insert_helper(root, i);
}
template<class T>
uniTreeNode<T> *uniBTree<T>::insert_helper(uniTreeNode<T> *current, const T i)
{
if (current == NULL) {//this is will only dealed by attempting to visit leaves...
//if root is null, it'll be handled in insert
uniTreeNode<T> *child = new uniTreeNode<T>(i, NULL, NULL);
assert(child != NULL);
return(child);
}
if (i < current->get_data())
current->set_left(insert_helper(current->get_left(), i));
else
current->set_right(insert_helper(current->get_right(), i));
return(current);
}
#endif
uniTreeNode.h
#ifndef uniTreeNode_H//for redefinition
#define uniTreeNode_H
#include <iostream>
//using namespace std; don't use using namespace xxx and include source file in .h file
template<typename T>
class uniTreeNode {
private:
T data;
uniTreeNode<T> *left;
uniTreeNode<T> *right;
public:
//uniTreeNode<T>(void);
uniTreeNode(T d, uniTreeNode<T> *l, uniTreeNode<T> *r);
T get_data(void) const;
uniTreeNode<T> *get_left(void) const;
uniTreeNode<T> *get_right(void) const;
void set_left(uniTreeNode<T> *l);
void set_right(uniTreeNode<T> *r);
void print() const;
};
template<typename T>
uniTreeNode<T>::uniTreeNode/*remember syntax here*/
(T d , uniTreeNode<T> *l = NULL, uniTreeNode<T> *r = NULL)
{
data = d;
left = l;
right = r;
}
template<typename T>
T uniTreeNode<T>::get_data(void) const
{
return data;
}
template<typename T>
uniTreeNode<T> * uniTreeNode<T>::get_left(void) const
{
return left;
}
template<typename T>
uniTreeNode<T> * uniTreeNode<T>::get_right(void) const
{
return right;
}
template<typename T>
void uniTreeNode<T>::set_left(uniTreeNode<T> *l)
{
left = l;
}
template<typename T>
void uniTreeNode<T>::set_right(uniTreeNode<T> *r)
{
right = r;
}
template<typename T>
void uniTreeNode<T>::print() const
{
std::cout << "data is " << data << std::endl;
}
#endif
date.h
#include <ostream>
class date{
private:
int y;
int m;
int d;
public:
date();//default constructor
date(const long int);//used by cplr as convert constructor
date(int, int , int);
friend bool operator<(const date &d1, const date &d2);//d1 is for left-hand date
friend bool operator>(const date &d1, const date &d2);
bool operator==(date d);
bool operator!=(date d);
date &operator=(date d);
friend std::ostream &operator<<(std::ostream &out, date d);
friend std::istream &operator>>(std::istream &in, date d);
};
date.cc
#include <iostream>
#include <cstdio>
#include <time.h>
#include <cstring>
#include "date.h"
date::date(){
y = m = d = 0;
}
date::date(int Y, int M, int D){
y = Y;
m = M;
d = D;
}
date::date(const long int s){//#second since 1970/1/1 00:00:00
struct tm *buf;
buf = gmtime(&s);
y = (buf->tm_year+1900);
m = buf->tm_mon+1;
d = buf->tm_mday;
}
bool operator<(const date &d1, const date &d2){
bool result;//sizeof(bool) is 1
if(d1.y < d2.y) result = true;
else if(d1.y == d2.y){
if(d1.m < d2.m) result = true;
else if(d1.m == d2.m){
if(d1.d < d2.d) result = true;
else result = false;
}
else result = false;
}
else result = false;
return result;
}
bool operator>(const date &d1, const date &d2){
bool result;//sizeof(bool) is 1
if(d1.y > d2.y) result = true;
else if(d1.y == d2.y){
if(d1.m > d2.m) result = true;
else if(d1.m == d2.m){
if(d1.d > d2.d) result = true;
else result = false;
}
else result = false;
}
else result = false;
return result;
}
bool date::operator==(date d){
return (this->y==d.y && this->m==d.m && this->d==d.d);
}
bool date::operator!=(date d){
return (this->y!=d.y || this->m!=d.m || this->d!=d.d);
}
date &date::operator=(date d){
this->y = d.y;
this->m = d.m;
this->d = d.d;
return *this;
}
std::ostream &operator<<(std::ostream &out, date d){
out << d.y << "/" << d.m << "/" << d.d << std::endl;
return out;
}
std::istream &operator>>(std::istream &in, date d){
in >> d.y >> d.m >> d.d ;
return in;
}
main function
#include "uniBTree.h"
#include "date.h"
#include <cstdio>
int main(){
date d1 = 100000000;//convert constructor
uniTreeNode<date> node(d1, NULL, NULL);
printf("%p %p\n", node.get_left(), node.get_right());
std::cout << node.get_data() << std::endl;
date d2 = 86401;
date d3 = 200000000;
uniBTree<date> btree(&node);
return 0;
}
I tested and found that its &node that is invalid. I think it is because it tries to "release" btree at the end of the program and when the root is encountered, because it points to node, it can't perform good thing.
I have two question:
if construct a node like what I did,(uniTreeNode<date> node(xxx, xxx, xxx);) was the object "NEW"ed by the program?
for the uniTreeNode<T> class template, I didn't write its destructor!! So, like what I say above, when node,which is pointed by root of btree, is to be released is there so-called "default destructor"? and is it called here ? And most importantly, is "DELETE" used by the program?
If one of the two question above is no, is it why the problem arise?
EDIT: now the problem is shown, but how can I adjust my code to fix this? any one any idea?
EDIT: just modify like this:
uniTreeNode<date> *nodeptr = new uniTreeNode<date>(d1, NULL, NULL);
p.s. if not indirectly using a pointer to refer to our root of the btree(thus using new), new isn't used, and delete shouldn't be used; by this choice, delete_helper of uniTreenode should use this:
if(n != root){
delete n;
count++;
}
but this does not solve the problem...
the ultimate question is:
"can we release object without using delete(because it isn't obtained from newing) in c++?"
REPLY:
My "release"/"allocated" is actually saying about the memory, without specifying HOW it is done...but it's a big issue anyway
You say "you can do that but it is almost always the wrong answer";you mean that I should use DELETE but not directly call the destructor?(actually that doesn't seem proper at all)
-->please justify here
Btw, for those instance NEWed by me, is it necessary for them to be DELETED by a statement if I want to release them? or they'll also be dealt like those automatic variable instance?(back when out of scope, by compiler)
-->please correct the above if needed
another Q: isn't there ANY existing statement I can use to do things, like what DELETE does, for those automatic instance? or, I can only call destructor, if I wish?
Answer to your questions:
No, it allocated memory on the stack at compilation time and just ran the constructor on that.
You can't delete a pointer not allocated using new. The compiler inserts a call to the destructor (default or not) for uniTreeNode when the object node is done in main().
So to surmise, you cannot use delete on a pointer that is not allocated using new.
Simplest fix would be to allocate node using new:
uniTreeNode<date>* node = new uniTreeNode<date>(d1);
uniBTree<date> btree(node);
Learn to use valgrind.
It tells you right away what the problem is, you're deleting a stack object in the uniBTree destructor
==23648== Invalid free() / delete / delete[] / realloc()
==23648== at 0x4A0736C: operator delete(void*) (vg_replace_malloc.c:480)
==23648== by 0x400D78: uniBTree<date>::delete_helper(uniTreeNode<date>*) (uniBTree.h:48)
==23648== by 0x400CD5: uniBTree<date>::~uniBTree() (uniBTree.h:56)
==23648== by 0x400B91: main (main.cc:17)
==23648== Address 0x7fefffab0 is on thread 1's stack
==23648==
The destructor calls delete but &node was not created by new (you can tell that because you didn't write new!)

Error C2039: 'next' : is not a member of 'chain<T>' with [T=Person] [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm working on implementing a chain data structure, using a specific set of pre-made templates. Upon compilation, I'm receiving the error in the title.
arrayList.h:
#ifndef arrayList_h
#define arrayList_h
#include <iostream>
#include "linearList.h"
using namespace std;
template<class T>
class arrayList : public linearList<T>{
public:
//constructor, copy constructor, destructor
arrayList(int initialCapacity = 10);
arrayList(const arrayList<T>&);
~arrayList() {delete [] element;};
//ADT methods
bool empty() const {return listSize == 0;};
int size() const {return listSize;};
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
//additional method
int capacity() const {return arrayLength;};
protected:
void checkIndex(int theIndex) const;
//throw illegalIndex if theIndex is invalid
T* element; //1D array to hold list elements
int arrayLength; //capacity of 1D array
int listSize; //number of elements in list
};
#endif
chain.h:
#ifndef chain_h
#define chain_h
#include <iostream>
#include "linearList.h"
#include "chainNode.h"
using namespace std;
template<class T>
class chain : public linearList<T>{
public:
// constructor and destructor
chain(int initialCapacity = 10);
//chain(const chain<T>&);
~chain();
// ADT methods
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(ostream& out) const;
protected:
void checkIndex(int theIndex) const;
chain<T>* firstNode;
int listSize;
};
#endif
chainNode.h:
#ifndef chainNode_h
#define chainNode_h
#include <iostream>
template <class T>
struct chainNode
{
// data members
T element;
chainNode<T> *next;
// methods
chainNode() {}
chainNode(const T& element)
{this->element = element;}
chainNode(const T& element, chainNode<T>* next)
{this->element = element;
this->next = next;}
};
#endif
chain.cpp:
#include "chain.h"
#include "person.h"
using namespace std;
template<class T>
chain<T>::chain(int initialCapacity){
// Constructor.
/*if (initialCapacity < 1){
ostringstream s;
s << "Initial capacity = "
<< initialCapacity << " Must be > 0";
throw illegalParameterValue(s.str());
}*/
firstNode = NULL;
listSize = 0;
}
template<class T>
chain<T>::~chain(){
// Chain destructor. Delete all nodes
// in chain.
while (firstNode != NULL){
// delete firstNode
chainNode<T>* nextNode = firstNode->next;
delete firstNode;
firstNode = nextNode;
}
}
template<class T>
T& chain<T>::get(int theIndex) const{
// Return element whose index is theIndex.
checkIndex(theIndex);
// move to desired node
chainNode<T>* currentNode = firstNode;
for (int i = 0; i < theIndex; i++)
currentNode = currentNode->next;
return currentNode->element;
}
template<class T>
int chain<T>::indexOf(const T& theElement) const{
// search the chain for theElement
chainNode<T>* currentNode = firstNode;
int index = 0; // index of currentNode
while (currentNode != NULL && currentNode->element != theElement){
// move to next node
currentNode = currentNode->next;
index++;
}
// make sure we found matching element
if (currentNode == NULL)
return -1;
else
return index;
}
template<class T>
void chain<T>::erase(int theIndex){
checkIndex(theIndex);
chainNode<T>* deleteNode;
if (theIndex == 0){
// remove first node from chain
deleteNode = firstNode;
firstNode = firstNode->next;
}
else{
// use p to get to beforeNode
chainNode<T>* p = firstNode;
for (int i = 0; i < theIndex - 1; i++)
p = p->next;
deleteNode = p->next;
p->next = p->next->next;
}
listSize--;
delete deleteNode;
}
template<class T>
void chain<T>::insert(int theIndex, const T& theElement){
if (theIndex < 0 || theIndex > listSize){
// THROW ILLEGAL EXCEPTION
}
if (theIndex == 0) // insert at front
firstNode = new chainNode<T>(theElement, firstNode);
else{
// find predecessor of new element
chainNode<T>* p = firstNode;
for (int i = 0; i < theIndex - 1; i++)
p = p->next;
// insert after p
p->next = new chainNode<T>(theElement, p->next);
}
listSize++;
}
Person.h:
#ifndef Person_h
#define Person_h
#include <string>
#include <sstream>
using namespace std;
class Person{
public:
//Variables
string birthdate;
string first_name;
string last_name;
string hometownID;
string hometownName;
string userID;
string name;
//Constructors
Person();
Person(string birthdate, string first_name, string last_name, string hometownID, string hometownName, string userID);
//Methods
string getBirthdate();
void setBirthdate(string birthdate);
string getFirst_name();
void setFirst_name(string first_name);
string getLast_name();
void setLast_name(string last_name);
string getName();
void setName(string name);
string getHometownID();
void setHometownID(string hometownID);
string getHometownName();
void setHometownName(string hometownName);
string getUserID();
void setUserID(string userID);
int compare(Person& p, int criteria);
//Comparisons
friend bool operator== (Person p1, Person p2);
friend bool operator!= (Person &p1, Person &p2);
friend bool operator> (Person &p1, Person &p2);
friend bool operator>= (Person &p1, Person &p2);
friend bool operator< (Person &p1, Person &p2);
friend bool operator<= (Person &p1, Person &p2);
friend ostream& operator<<(ostream& os, const Person& p);
};
#endif
Person.cpp: I've cut this down quite a bit. I currently don't have anything having to do with Node within this.
#include "Person.h"
#include <sstream>
#include <string>
using namespace std;
Person::Person(){
birthdate = "";
name = "";
hometownID = "";
hometownName = "";
userID = "";
}
Person::Person(string birthdate, string first_name, string last_name, string hometownID, string hometownName, string userID){
this->birthdate = birthdate;
this->first_name = first_name;
this->last_name = last_name;
this->hometownID = hometownID;
this->hometownName = hometownName;
this->userID = userID;
name = last_name+ ", " +first_name;
}
//mostly get/set methods after here, nothing having to do with node.
main.cpp:
#include "arrayList.cpp"
#include "block_allocator.h"
#include "chain.cpp"
#include "chainNode.h"
#include "json.h"
#include "linearList.h"
#include "Person.h"
#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <time.h>
using namespace std;
//ArrayList helper methods
arrayList<Person> arrayListStructure(string fileName);
int arrayListSort(int criteria, arrayList<Person>* list);
void arrayListReverseSort(int criteria, arrayList<Person>* list);
int arrayListFlip(arrayList<Person>* list);
//Chain helper methods
chain<Person> chainStructure(string fileName);
//Hashtable helper methods
int main(int argc, const char * argv[]){
//get fileName
cout << "Please enter a filename:" << endl;
string fileName;
cin >> fileName;
//get data structure type
cout << "Please choose a data structure:" << endl;
cout << " 1. Arraylist" << endl;
cout << " 2. Chain" << endl;
cout << " 3. Hashtable" << endl;
int dataStructure;
cin >> dataStructure;
cout << "Please choose a criteria:" << endl;
cout << " 1. Name" << endl;
cout << " 2. Birthday" << endl;
cout << " 3. Location" << endl;
int criteria;
cin >> criteria;
arrayList<Person> friends;
chain<Person> friendChain;
//parse file into data structure
switch(dataStructure){
case 1: //Arraylist
//edited out, irrelevant
/*case 2:
//Chain
//code goes here
/*switch(criteria){
case 1: //Name
case 2: //Birthday
case 3: //Location
}
break;*/
/*case 3:
//Hashtable
//code goes here
break;
*/
}
}
//Helper methods for chain
chain<Person> chainStructure(string fileName){
//create initial (empty) chain
chain<Person> friends;
//open input file
ifstream fileInput(fileName);
//turn input stream into string
string inputStr((istreambuf_iterator<char>(fileInput)), istreambuf_iterator<char>());
//parse file content into json object
char *errorPos = 0;
char *errorDesc = 0;
int errorLine = 0;
block_allocator allocator(1 << 10);
json_value *root = json_parse(const_cast<char*>(inputStr.c_str()), &errorPos, &errorDesc, &errorLine, &allocator);
//Take value of first element
json_value *list = root->first_child;
//Outer loop addresses each friend's JSON object
for(json_value *it = list->first_child; it; it = it->next_sibling){
string first_name, last_name, birthdate, hometownID, hometownName, userID;
//Inner loop looks at each key/value pair within each friend object
for(json_value *friendKeys = it->first_child; friendKeys; friendKeys = friendKeys->next_sibling){
//grab first name
if(!string(friendKeys->name).compare("first_name")){
first_name = friendKeys->string_value;
}
//grab last name
else if(!string(friendKeys->name).compare("last_name")){
last_name = friendKeys->string_value;
}
//grab birthday and trim to 5 characters
else if(!string(friendKeys->name).compare("birthday")){
birthdate = friendKeys->string_value;
birthdate = birthdate.substr(0, 5);
}
//grab hometown info
else if(!string(friendKeys->name).compare("hometown")){
for(json_value *hometownKeys = friendKeys->first_child; hometownKeys; hometownKeys = hometownKeys->next_sibling){
if(!string(hometownKeys->name).compare("id")){
hometownID = hometownKeys->string_value;
}
if(!string(hometownKeys->name).compare("name")){
hometownName = hometownKeys->string_value;
}
}
}
//grab userID
else if(!string(friendKeys->name).compare("id")){
userID = friendKeys->string_value;
}
}
if(birthdate != "" && first_name != "" && last_name != "" && hometownID != "" && hometownName != "" && userID != ""){
//Create new Person in chain
Person person(birthdate, first_name, last_name, hometownID, hometownName, userID);
friends.insert(friends.size(), person);
}
}
//return friends;
return friends;
}
//Helper methods for hashtable
So I know this is a huge wall of text, but I'm really not sure where this disconnect is, and I didn't want to provide too little information. Any help or advice would be greatly appreciated, as I'm very new to C++, and even more inexperienced with using the template system.
EDIT: linearList.h:
#ifndef linearList_h
#define linearList_h
#include <iostream>
using namespace std;
template<class T>
class linearList
{
public:
virtual ~linearList() {};
virtual bool empty() const = 0;
// return true iff list is empty
virtual int size() const = 0;
// return number of elements in list
virtual T& get(int theIndex) const = 0;
// return element whose index is theIndex
virtual int indexOf(const T& theElement) const = 0;
// return index of first occurence of theElement
virtual void erase(int theIndex) = 0;
// remove the element whose index is theIndex
virtual void insert(int theIndex, const T& theElement) = 0;
// insert theElement so that its index is theIndex
virtual void output(ostream& out) const = 0;
// insert list into stream out
};
#endif
In chain.h, the chain<T> template has this for a member:
chain<T>* firstNode;
I'm pretty sure that should be:
chainNode<T>* firstNode;
There may be other errors (or maybe not), but that appears the likely one causing your current issue that is the subject of this question.
Side Bar: This thing needs a serious refactor to use the containers and algorithms from the standard library (std::vector<T>, std::list<T>, etc...) Just consider it.