Djole
Djole

Reputation: 142

Segmentation error in simple inheritance related code

Shortened code I wrote for learning purposes. Still the way it is, it doesn't work properly. Removing last line (&&) it works OK, but with it, code doesn't reach line noted as ##, expressing segmentation error, after the "BazOnly" text displayed.

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

namespace nek{
    class Baz{
        int num; 
        std::string  str;
        public:
        Baz(){cout<<"BazOnly"<<endl;}
        string setstr(string& val){  
            //str.assign(val);
            num= 7;
        }
    }; 
}

namespace drg{
    class Deriv: nek::Baz{       
        public:
        Deriv(char ch){cout<<"DerivChar"<<endl;}
    };
};

int main(){
    nek::Baz b;     
    string priv{"zik"};
    b.setstr(priv);    
    cout<<"Passed here"<<endl; //##
    drg::Deriv dc{'A'};  // &&
}

Compiled with g++ (option std=gnu++11), Ubuntu 16 on Virtual Box. Question is what could be the reason for such behavior ?

Upvotes: 1

Views: 36

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118330

    string setstr(string& val){  
        //str.assign(val);
        num= 7;
    }

This method is declared as returning a std::string, but nothing actually gets returned from it. This is undefined behavior.

Most modern C++ compilers will warn you about this. If yours' did, this is an example of why you cannot ignore warning messages from your compiler, even if it did successfully compile your code.

Upvotes: 3

Related Questions