0

I'm trying to set up a basic class using std::string as a function type and a variable type, but using both gives me a segmentation fault. If I delete either the function or the variable, everything is fine. I'm sure I'm making a really stupid mistake! This is my code: main.cpp

#include <iostream>
#include <cstdlib>
#include <string>
#include "myclass.h"

int main()
{

    myclass obj;
    obj.replace();

    return EXIT_SUCCESS;
};

myclass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_
#include <string>

class myclass
{
    private:
        std::string instruction;

    public:
        myclass();
        std::string replace();
}; 

#endif

myclass.cpp

#include "myclass.h"
#include <iostream>


myclass::myclass()
{
    std::cout<<"I am the constructor"<<std::endl;
}

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
}
6
  • 6
    For starters, you said you'd return an std::string from myclass::replace and you didn't, so that's an issue. Commented Mar 10, 2014 at 16:33
  • I am impressed you even reach a seg fault. Compiler should at least warn you if not return an error. Commented Mar 10, 2014 at 16:34
  • Added a return statement in and tada! Thanks very much faranwath Commented Mar 10, 2014 at 16:40
  • @faranwath Add you answer, you'll get upvote on it instead of your comment. Commented Mar 10, 2014 at 16:42
  • @EricFortin: Sadly, some popular compilers don't give warnings (let alone reject code with warnings) unless you tell them to. Commented Mar 10, 2014 at 17:04

2 Answers 2

2

You said myclass::replace was to return an std::string every time it gets called, but you didn't actually returned anything! What happened then enters the realm of undefined behavior, which usually means your program will misbehave and eventually could even kill your cat.

The solution is to add a return statement at the end of the function.

Sign up to request clarification or add additional context in comments.

Comments

1

Here

obj.replace();

you have discarded return value, std::string You can discard the return value. It's no good style in general, but you can always do it. But the actual problem is that you don't return anything from replace function:

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
    //... return statement is missing
}

solution:

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
    return std::string();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.