class - C++ classes, segmentation fault when calling member function -
i learning c++ , have been experimenting classes head around how work. have programmed classes in java before now.
in code have class definition , driver test. in comments have mention works , doesn't. want know why instantiating objects 1 way works in other ways errors. compiler, make file, or class code? constructor/default constructor? when compare code others textbook, can't see i've gone wrong.
using: code::blocks 10.5 on linux mint 13.
header file:
#ifndef enemy_h #define enemy_h #include <string> using namespace std; class enemy { public: enemy(); enemy(int, int, string); ~enemy(); string display(); // setter , getters: int gethp(); void sethp(int); int getx(); void setx(int); int gety(); void sety(int); string getname(); void setname(string); private: int hitpoints; int x_pos; int y_pos; string name; }; #endif // enemy_h
member function defifnitions:
#include "enemy.h" #include <iostream> #include <string> // default ctor enemy::enemy() { cout << "creating enemy default ctor.\n"; } //ctor enemy::enemy(int x, int y, string str) { cout << "creating object name: " << str << endl; setx(x); sety(y); sethp(100); setname(str); } //dtor enemy::~enemy() { cout << "destroying enemy: " << name << endl; } string enemy::display() { cout<<name<<" - x: "<<x_pos<<", y: "<<y_pos<<", hp: "<<hitpoints<<endl; } int enemy::gethp(){ return hitpoints; } void enemy::sethp(int hp){ hitpoints = hp; } int enemy::getx(){ return x_pos; } void enemy::setx(int x){ x_pos = x; } int enemy::gety(){ return y_pos; } void enemy::sety(int y){ y_pos = y; } string enemy::getname(){ return name; } void enemy::setname(string objectname){ name = objectname; } // end of function definitions
driver:
#include "enemy.h" #include <iostream> #include <string> using namespace std; int main() { cout << "program started.\n" << endl; // initialise few enemy objects enemy e1(1, 1, "e1"); enemy e2(2, -4, "e2"); enemy e3; enemy e4; enemy *e5 = new enemy(4, 5, "e5"); e1.display(); // <- success! e2.display(); // <- success! e3.display(); // <- segmentation fault @ run time e4.display(); // <- segmentation fault @ run time e5.display(); // <- compile time error "request member // 'display'" in 'e5'. of // non-class type 'enemy' cout << "end of program.\n"; return 0; }
what's causing segfault fact you're flowing off edge of function that's supposed return string
(which undefined behavior):
string enemy::display() //^^^^ you're supposed return string { cout<<name<<" - x: "<<x_pos<<", y: "<<y_pos<<", hp: "<<hitpoints<<endl; // no return statement }
the rest in @chris' answer.
Comments
Post a Comment