Home > Net >  C class object default constructor bug
C class object default constructor bug

Time:07-02

I am trying to create a class object s2 with some customized attributes and some attributes from default constructor however my output is the wrong output for the get_year function. It should be outputing 0 which is the key for FRESHMAN but it is out putting 2 instead. The rest of the code is outputting as expected:

#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
#include <ctime>
#include <vector>
#include <cctype>

using namespace std;


enum year {FRESHMAN, SOPHOMORE, JUNIOR, SENIOR};
struct name
{
    string firstName;
    string lastName;
    friend std::ostream& operator <<(ostream& os, const name& input)
    {
        os << input.firstName << ' ' << input.lastName << '\n';
        return os;
    }
};
class Student: name{

    private:
        name Name;
        year Year;
        int idNumber;
        string Department;


    
    
    




    public:
    void setname(string fn="", string ln="")
    {
        Name.firstName =fn;
        Name.lastName =ln;
    }
    name get_name()
    {
        return Name;
    }
    void set_year(year yr=FRESHMAN)
    {
        Year=yr;
    }
    year get_year()
    {
        return Year;
    }
    void set_ID(int ID=0)
    {
        idNumber=ID;
    }
    int get_ID()
    {
        return idNumber;
    }
    void set_Department(string Dept="")
    {
        Department=Dept;
    }
    string get_Department()
    {
        return Department;
    }

};
int main()
{
    Student s2;
    s2.setname("Nikolai", "Khabeboolin");
    s2.set_ID(12436193);

    cout<<"ID is: "<< s2.get_ID()<<", name is "<< s2.get_name()<<", year in school is: "<<s2.get_year()<<", Department is "<<s2.get_Department()<<endl;
    return 0;
}

CodePudding user response:

Student lacks a constructor, so all its members are default initialized, and the default initialization of year Year and int idNumber is "no initialization", so reading from them is undefined behavior. Reading them might find 0, 2, a random value each time, or crash.

I see that your class contains a void set_year(year yr=FRESHMAN) member, but your code never called set_year, so no part of this executed.

You should make a default constructor for Student, or as Goswin von Brederlow stated, use year Year{FRESHMAN}; and int idNumber{-1}; when declaring the members, to give them default initializations.

CodePudding user response:

By not explicitly declaring and defining a constructor, in this case Student(), you open yourself up to undefined behavior. Your constructor should call set_year(year yr=FRESHMAN) OR even better, just set the year itself.

  • Related