Segmentation fault during runtime of console code in C++

家住魔仙堡 提交于 2019-12-11 15:23:26

问题


I'm trying to make a simple console student details display system whereby there are 2 classes, class student(Base class) with member variables for name and registration number and class studentAthlete(Derived class) with sports type string. The code compiles sucessfully but on runtime only asks for student details but does not display the details as would be expected when I call the identify() function. On code blocks, the error might not show but on online compiles such as https://www.onlinegdb.com/online_c++_compiler it shows that there is a Segmentation fault in the code. Please assist where necessary.

My code is exactly(in whole) as is below:

#include <iostream>
using namespace std;

/**Base class**/
class student
{
protected:
    string studName, studRegNum;
public:
    student(string stdName, string regNo);
    /**To define friendly class that is
    Common to both classes**/
    friend void identify();
};
/**constructor for class student**/
student::student(string stdName, string regNo)
{
    studName = stdName;
    studRegNum = regNo;
}
/**Derived class**/
class studentAthlete : public student
{
private:
    string member_sport;
public:
    /**To create constructor for class studentAthlete within class**/
    studentAthlete(string student_sport):student(studName, studRegNum)
    {
        member_sport = student_sport;
    }
    /**To define friendly class that is
    Common to both classes**/
    friend void identify();
};

/**To display student information**/
void identify()
{

    studentAthlete sa(sa.member_sport);
    cout<<"Student Name: "<<sa.studName<<endl;
    cout<<"Student Registration Number: "<<sa.studRegNum<<endl;
    cout<<"Student Sport: "<<sa.member_sport<<endl;

}

int main()
{
    string StudentName, StudentRegistrationNo, StudentSport;
    /**To get & set student name from user**/
    cout<<"Enter student name: "<<endl;
    cin>>StudentName;

    /**To get & set Student Registration No from user**/
    cout<<"Enter Student Registration No: "<<endl;
    cin>>StudentRegistrationNo;

    /**To get & set Student Sport from user**/
    cout<<"Enter Student Sport: "<<endl;
    cin>>StudentSport;

    /**To pass student values to their respective constructors**/
    student st(StudentName,StudentRegistrationNo);
    studentAthlete sa(StudentSport);

    /**To display student information**/
    identify();
    return 0;
}

回答1:


You’re passing uninitialised members to the Student constructor.
This will cause undefined behaviour.

You need to add name and number parameters to the athletes’ constructor and pass those to Student.



来源:https://stackoverflow.com/questions/55695750/segmentation-fault-during-runtime-of-console-code-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!