I'm working on a program to create and display a Pythagoras Tree using SFML in C++. The class I've created inherits from the SFML class Drawable which has the pure virtual function "draw" and I believe the segFault is coming from my definition of this function.
#include <cmath>
#include <SFML/Graphics.hpp>
#include <vector>
class PTree: public sf::Drawable{
public:
PTree(float length);
PTree(sf::RectangleShape shape);
~PTree(){};
void pTree(int depth);
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
private:
sf::RectangleShape square;
PTree* leftPoint;
PTree* rightPoint;
bool hasNext;
};
PTree::PTree(float length){
sf::Vector2f size(length,length);
sf::RectangleShape shape(size);
square = shape;
square.setFillColor(sf::Color::Red);
square.setPosition(5.5*length,6.5*length);
hasNext = true;
}
PTree::PTree(sf::RectangleShape shape){
square = shape;
square.setFillColor(sf::Color::Red);
hasNext = true;
}
void PTree::pTree(int depth){
if(depth == 0){
this->leftPoint = NULL;
this->rightPoint = NULL;
this->hasNext = false;
return;
}
sf::Vector2f oldSize = this->square.getSize();
float oldL = oldSize.x;
float newL = sqrt(pow(oldL,2)/2);
sf::Vector2f newSize(newL,newL);
sf::Vector2f point1 = this->square.getPoint(0);
sf::Vector2f point2 = this->square.getPoint(1);
sf::RectangleShape left(newSize);
sf::RectangleShape right(newSize);
left.setOrigin(0,0-newL);
right.setOrigin(newL,0-newL);
left.setPosition(point1);
right.setPosition(point2);
left.rotate(45);
right.rotate(-45);
PTree Left(left);
PTree Right(right);
leftPoint = &Left;
rightPoint = &Right;
Left.pTree(depth-1);
Right.pTree(depth-1);
}
void PTree::draw(sf::RenderTarget& target, sf::RenderStates states) const{
target.draw(this->square);
if(!hasNext){
return;
}
PTree& leftTree = *leftPoint;
PTree& rightTree = *rightPoint;
leftTree.draw(target,states); //this is where the error occurs
rightTree.draw(target,states);
}
int main(int argc, char* argv[]){
float length = atof(argv[1]);
int depth = atoi(argv[2]);
PTree tree(length);
tree.pTree(depth);
float windowH = 8 * length;
float windowW = 12 * length;
sf::RenderWindow window(sf::VideoMode(windowW,windowH), "Pythagoras Tree");
while(window.isOpen()){
sf::Event event;
while(window.pollEvent(event)){
if(event.type == sf::Event::Closed)
window.close();
}
window.clear();
tree.draw(window,sf::RenderStates::Default);
window.display();
}
}
After some debugging I found out that the segmentation Fault happens in the line leftTree.draw(target,state);
in my draw function. I looked around online because I'm still a beginner and I know that this kind of error can be caused by pointers or recursion, I'm using both here so I dont know which is my problem. However, I added a print statement to test at the beginning of my function and it only prints once when I run the program so I'm assuming it has to do with my pointer rather than recursion. Any help is appreciated!