I assign the value data member why need to use constructor??
I can not create a class constructor and I assign the value of my variable and my code run without creating a constructor?? so why use constructor
my question is We can directly assign value to any data member. see my code:
#include <iostream>
#include <conio.h>
class calculator {
public:
int n1=100;
char grade='a';
// public:
// calculator()
// {
// grade='a';
// n1=100;
// }
void display()
{
std::cout << "first value:" <<grade<< std::endl;
std::cout << "second value:" <<n1<< std::endl;
}
};
int main()
{
calculator cal;
cal.display();
return 0;
}
o/p is:
- first value:a
- second value:100
and when
#include <iostream>
#include <conio.h>
class calculator {
int n1;
char grade;
private:
calculator()
{
grade='A';
n1=100;
}
void display()
{
std::cout << "first value:" <<grade<< std::endl;
std::cout << "second value:" <<n1<< std::endl;
}
};
int main()
{
calculator cal;
cal.display();
return 0;
}
and suddenly i want to access private data members for example(employee salary) then how to access private data??