CVDH CVDH - 2 months ago 17
C++ Question

C++: Segmentation fault on base class constructor

Why does it produce a segmentation fault when I create a Rectangle object? I'm thinking that there is something about my constructors that is incorrect but I don't have enough experience in C++ to identify what.

#include <string>
#include <map>

using namespace std;

class Shape {
private:
string name;
string property_name;
map<string,double> parameters;


public:
Shape(){
}

void set_name(string n){
name=n;
}

string set_property_name(string s){
property_name=s;
}

void set_parameter(string p, double n){
parameters[p]=n;
}

double get_parameter(string p) {
return parameters[p];
}

virtual double get_property() = 0;

};

class Shape2D: public Shape {
public:
Shape2D() {
set_property_name("area");
}
};

class Rectangle: public Shape2D {
public:
Rectangle() {
set_name("rectangle");
set_parameter("length",0);
set_parameter("base",0);
}

double get_property() {
return get_parameter("length") * get_parameter("base");
}
};


int main() {
Shape * user_shape;
user_shape=new Rectangle();
return 0;
}

Answer

Because your string set_property_name(string s) have no return and is undefined behavior

Comments