I recently began to learn object oriented programming and now I'm faced with the problem of changing program with usual pointers to program with shared_ptr. I try to create a program with a container (n-tree), which contains twi types of figures: Hexagons and Rhombuses. And I must also use shared_ptr. The first question is: For example, I have a function, that adds an element to n-tree:
tnode *add(tnode **node, const Figure figure) {
tnode *pnext = NULL;
tnode *p = (tnode *)malloc(sizeof(tnode));
p->data = rhombus;
p->parent = NULL;
p->prev = NULL;
p->next = NULL;
p->child = NULL;
if (*node == NULL)
*node = p;
else if ((*node)->child == NULL) {
p->parent = *node;
(*node)->child = p;
} else {
pnext = (*node)->child;
while (pnext->next != NULL)
pnext = pnext->next;
p->parent = *node;
p->prev = pnext;
pnext->next = p;
}
return p;
}
...or destroys the tree:
void destroy(tnode **node) {
if (*node == NULL)
return;
if ((*node)->next != NULL)
destroy(&(*node)->next);
if ((*node)->child != NULL)
destroy(&(*node)->child);
free(*node);
*node = NULL;
}
How it will look with std::shared_ptr? And the second problem is that compilator doesn't see that Figure is a parent class for other two figures:
Figure.h
class Figure {
public:
virtual bool operator==(const Figure& right);
virtual &Figure::operator=(const Figure& right);
virtual double Square() = 0;
virtual void Print() = 0;
virtual ~Figure(){}
};
Hexagon.h
#include "Figure.h"
class Hexagon : public Figure{
public:
Hexagon();
Hexagon(std::istream &is);
Hexagon(float side);
Hexagon(const Hexagon& orig);
bool operator==(const Hexagon& right);
Hexagon& operator=(const Hexagon& right);
double Square() override;
void Print() override;
virtual ~Hexagon();
//private:
int side;
};
Rhombus.h
#include <cstdlib>
#include <iostream>
#include "Figure.h"
class Rhombus : public Figure{
Rhombus();
Rhombus(std::istream &is);
Rhombus(int side, float angle);
Rhombus(const Rhombus& orig);
bool operator==(const Rhombus& right);
double Square();// override;
Rhombus& operator=(const Rhombus& right);
virtual ~Rhombus();
//private:
int side;
float angle;
};
In functions "add" and "destroy" (where a parameter is A Figure) compiler also writes "cannot declare field figure to be of abstract type Figure"
And the last question. As I understand, in a structure of N-Tree one part of structure "ownes" some others, so wear_ptr are needed. Is there a mistake?
struct tnode {
Figure data;
std::weak_ptr<tnode>parent;
std::weak_ptr<tnode>prev;
std::shared_ptr<tnode>next;
std::shared_ptr<tnode>child;
~tnode();
};
So, could you say me, where I am wrong and how to solve the problem.