Can I use constant variables and simple or constant function in the same program?

39 Views Asked by At

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?

2

There are 2 best solutions below

0
Tony Delroy On

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, allowing student 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 the const member variables, as you do in your custom constructor. So, it's good that student 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 the const members and have a way of setting them after the default constructor has run, which is a bit ugly!

0
stefaanv On

You don't have a constructor without parameters, so you can't make an object without passing parameters. Overcome it, by either making a default constructor or not making an object without parameters.

The confusing part may be that you can make an object without parameters if you didn't make any constructor, but from the moment a constructor is made, the default constructor must also be made if needed. This can be done with:

student() : roll(0), name("");

Even though that probably doesn't make a lot of sense, so you're best in not using student o;.