I haven't done C++ coding in some time, and my friend is having trouble with his homework. I never really worked with const
, and it's making this a nightmare as I can't figure out the correct syntax for the constructor. Imagine I have this in dvd.h
:
class DVD {
const string title;
int minutes;
double price;
public:
DVD(const string t, int m, double p);
}
3 private member variables, the string
is const
. The constructor also takes a const string
.
So now, in dvd.cpp
I can do the following:
#include "dvd.h"
DVD::DVD(const string t, int m, double p) {
const string title = t;
minutes = m;
price = p;
}
And all is well in the world. However, when I modify minutes
in dvd.h
to be const
(which is how his professor structured the file), we have this in dvd.h
:
class DVD {
const string title;
const int minutes; // Here is the change
double price;
public:
DVD(const string t, int m, double p);
}
So, now that minutes
is const
, I get the following compilation errors:
assignment of read-only member 'DVD::minutes' dvd.cpp
uninitialized member 'DVD::minutes' with 'const' type 'const int' [-fpermissive] dvd.cpp
Which I suppose makes sense, because I'm trying to set a value into a const
variable. So then I tried doing the same thing as with the const string title
in dvd.cpp
in order to resolve the error:
DVD::DVD(const string t, int m, double p) {
const string title = t;
const int minutes = m; // Was 'minutes = m;'
price = p;
}
and got the following (1) errors and (1) warnings:
uninitialized member 'DVD::minutes' with 'const' type 'const int' [-fpermissive] dvd.cpp
unused variable 'minutes' [-Wunused-variable] dvd.cpp
So I guess I'm struggling to figure out what the darn syntax is for this... title
and minutes
are supposed to be const
, but the constructor's parameter list for DVD
takes only a const string
. I can't figure out what I'm missing - it's been a while since I last coded in C++.