Why is my output stream seg faulting and my virtual destructor does not work but when i kill virtual it does

StackOverflow https://stackoverflow.com//questions/9610006

  •  09-12-2019
  •  | 
  •  

Question

I am reviewing for a test and I am working on my personal project but I am doing incremental development. I want to do well in my university studies.

It seg faults on my ostream operator and my virtual function does not work unless its with out virtual .

    #include"MyString.h"





 MyString::MyString( )  //constructor
 {
     size=0;
     capacity=1;
     data=new char[capacity];

 }
  MyString::MyString(char * n)  //copy constructor
 {
     size=strlen(n);
     capacity=strlen(n)+1;
   data=new char[capacity];
   strcpy(data,n);
 }
  MyString::MyString(const MyString &right)  //
 {
     size=strlen(right.data);
     capacity=strlen(right.data)+1;
   data=new char [capacity];
   strcpy(data,right.data);

 }
   MyString::~MyString( )
 {
  delete [] data;
 }
 MyString  MyString::operator = (const MyString& s)
 {

     if(this!=&s)
{
    MyString temp=data;
    delete [] data;
    size=strlen(s.data);
    capacity=size+1;
    data= new char [capacity];
    strcpy(data,s.data);
}
 }
 MyString&  MyString::append(const MyString& s)
 {
    if(this!=&s)
    {
        strcat(data,s.data);
    }


 }
 MyString&  MyString::erase()
 {

 }
 MyString  MyString::operator + (const MyString&)const
 {

 }
 bool  MyString::operator == (const MyString&)
 {

 }
 bool  MyString::operator <  (const MyString&)
 {

 }
 bool  MyString::operator >  (const MyString&)
 {

 }
 bool  MyString::operator <= (const MyString&)
 {

 }
 bool  MyString::operator >= (const MyString&)
 {

 }
 bool  MyString::operator != (const MyString&)
 {

 }
 void  MyString::operator += (const MyString&)
 {

 }
 char&  MyString::operator [ ] (int)
 {

 }
 void  MyString::getline(istream&)
 {

 }
 int  MyString::length( ) const
 {
     return strlen(data);
 }


ostream& operator<<(ostream& out, MyString& s){

 out<<s;
 return out;


}



// int  MyString::getCapacity(){return capacity;}
Was it helpful?

Solution

The operator<<(), as implemented, is an infinite recursive call:

ostream& operator<<(ostream& out, MyString& s){
    out<<s;
    return out;
}

and will result in a stack overflow.

I think you meant:

ostream& operator<<(ostream& out, MyString& s){
    out << s.data;
    return out;
}

OTHER TIPS

I think this will work better not sure though (I suppose data is a 0 terminated c-string).

ostream& operator<<(ostream& out, MyString& s) {
    out<<s.data;
    return out;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top