Objects as members of classes

So I am trying to write a class called undergraduate that takes an object of the Phone class as an argument. However, the phone class uses a const data member called msg. This will not compile because of the const data member in the phone class. How do I fix it? Any help will be greatly appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

//Below is my default constructor for the Phone class, it uses const data member msg

Phone::Phone():msg(10){ //intialize const data member

        areacode = 999;

        exchange = 999;

        line = 9999;
}

//here is my constructor that takes objects as arguments

Undergraduate::Undergraduate(Name sname, Date bday, Program sprogram, Phone sphone, char g, string s, int c, double G, int gdyr, string term){

        name = sname;
        date = bday;
        pgm = sprogram;
        phone = sphone;

        gender = g;
        status = s;
        credit = c;
        gpa = G;
        gradyear = gdyr;
        gradterm = term;
}

 
Last edited on
To solve this issue you should initialize the member variables in the constructor initialization list, like you do with msg in the Phone constructor.
Last edited on
Thank you so much for responding. How exactly would I go about doing this?
You list the member variables, followed by the value they should be initialized with inside parentheses, separated by comma after the ) and before the {.

This is how it would look like for the Phone constructor.

 
Phone::Phone() : msg(10), areacode(999), exchange(999), line(9999) { }

You only strictly need to do this for the members that you can't assign to later, like Phone::msg and Undergraduate::phone, but it's generally considered the prefered way to initialize member variables so I recommend doing it for all of them.
Last edited on
thanks!
Topic archived. No new replies allowed.