Unable to find segmentation fault error in c++ -
i have 3 c++ files, instrument.h, percussion.h, , instrumentapp.cpp
. instrument.h
base class , percussion.h
inherits it. percussion
objects defined , implemented in instrumentapp.cpp
class. whenever run instrumentapp.cpp
, segmentation fault error.
i have managed trace cause of error overloaded << operator
function in percussion.h
calling method of base class instrument.h
. reason, code unable call methods of base class , don't know why. can please me?
here instrument.h class
#ifndef instrument_h #define instrument_h class instrument{ private: std::string name; std::string sound; std::string lowrange; std::string highrange; public: instrument(std::string name, std::string sound, std::string lowrange, std::string highrange){ this->name = name; this->sound = sound; this->lowrange = lowrange; this->highrange = highrange; } std::string getname() const{ return this->name; } std::string play()const { return this->sound; } std::string getlowrange() const{ return this->lowrange; } std::string gethighrange() const{ return this->highrange; } bool iswind(); bool iswoodwind(); bool isbrass(); bool iskeyboard(); bool ispercussion(); bool isstrings(); friend std::ostream &operator <<(std::ostream &os, const instrument &instrument){ } }; #endif
here percussion.h class
#ifndef percussion_h #define percussion_h #include "instrument.h" class percussion : public instrument{ private: bool struck; public: percussion(std::string name, std::string sound, std::string lowrange, std::string highrange, bool struck) : instrument(name,sound,lowrange,highrange){ this->struck=struck; } bool isstrucked() const { return this->struck; } bool ispercussion() { return true; } std::string gettype() const{ if(this->struck){ return "struck"; } else{ return ""; } } friend std::ostream &operator <<(std::ostream &os, percussion &percussion){ //the error stems line of code //apparently, getname() method in base class isn't called os<<percussion.getname(); } }; #endif
here implementation file instrumentapp.cpp
#include <iostream> #include <string> #include <sstream> #include <cstdlib> #include "instrument.h" #include "percussion.h" #include "strings.h" using namespace std; int main() { percussion timpani("timpani", "boom", "d2", "a2", true); cout << timpani << endl; percussion harp("harp", "pling", "cb1", "f#7", false); cout << harp << endl; return 0; }
the problem here wasn't returning os object when overloaded << operator.
the fix follows in percussion.h
file
friend std::ostream &operator <<(std::ostream &os, percussion &percussion){ os<<percussion.getname(); return os; }
Comments
Post a Comment