constant variables and functions in the same program cpp
#include<bits/stdc++.h>
using namespace std;
class student
{
public:
const int roll;
const string name;
student (int r,string n)
:roll(r),name(n)
{
cout<<roll<<endl;
cout<<name<<endl;
}
void display()
{
cout<<"Disp\n";
}
};
int main()
{
student obj(2003081,"ismail");
student o; //ERROR
o.display();
return 0;
}
I can't understand, why the compiler shows "no matching function for call to 'student::student()' "? Where is the problem and how can I overcome this?
When you write a class with a custom constructor (in your case,
student (int r,string n), the compiler won't also generate a default constructor (i.e. one that doesn't expect any arguments, allowingstudent o;to compile). It probably wouldn't make sense to have a default constructor for your class, as you need to get values somehow to initialise theconstmember variables, as you do in your custom constructor. So, it's good thatstudent o;is an error. That said, sometimes there are reasons to want a default-constructible type (for example, some container you want to use may insist on it). Then you have to get rid of theconstmembers and have a way of setting them after the default constructor has run, which is a bit ugly!