I am playing with a sort of linked list using C++ classes. I have used a lot of C linked lists (struct based) during C programming course, but there was no behavior. Thus, I am a bit confused about the correct definition of a class containing a pointer to another object of the same class. Here is the header:
#ifndef CONNECTEDPOINT_H
#define CONNECTEDPOINT_H
#include "vector3d.h"
class ConnectedPoint
{
using Position = Vector3D<double>;
public:
ConnectedPoint(unsigned index, const Position& pos);
~ConnectedPoint();
ConnectedPoint(const ConnectedPoint& point);
ConnectedPoint& operator=(const ConnectedPoint& point);
void connectTo(const ConnectedPoint& point);
unsigned index() const {return m_index;}
const Position& position() const {return m_position;}
Position& position() {return m_position;}
ConnectedPoint* getNext() {return next;}
private:
unsigned m_index;
Position m_position;
ConnectedPoint* next;
};
#endif // CONNECTEDPOINT_H
and the implementation file:
#include "connectedpoint.h"
ConnectedPoint::ConnectedPoint(unsigned index, const ConnectedPoint::Position& pos)
: m_index(index)
, m_position(pos)
, next(nullptr)
{
}
ConnectedPoint::~ConnectedPoint()
{
if(next != nullptr)
{
delete next;
next = nullptr;
}
}
ConnectedPoint::ConnectedPoint(const ConnectedPoint& point)
: m_index(point.m_index)
, m_position(point.m_position)
{
if(point.next == nullptr)
{
this->next = nullptr;
}
else
{
next = new ConnectedPoint(*(point.next));
}
}
ConnectedPoint& ConnectedPoint::operator=(const ConnectedPoint& point)
{
if(this == &point)
{
return *this;
}
delete next;
next = nullptr;
m_index = point.m_index;
m_position = point.m_position;
if(point.next != nullptr)
{
next = new ConnectedPoint(*(point.next));
}
return *this;
}
void ConnectedPoint::connectTo(const ConnectedPoint& point)
{
next = new ConnectedPoint(point.index(),point.position());
*(next->next) = *(point.next);
}
Vector3D is just a class template which holds 3 coordinates and allows standard mathematical vector operations. Here its behaviors are not used.
Basically I would like to know:
Is this a proper implementation for such a class? Are there mistakes both in the approach and in the implementation?