Search code examples
c++oopconstructorgetter-setter

C++ class object default constructor bug


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;
}

Solution

  • 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.