constant object issued no compiler error | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

constant object issued no compiler error

In previous section, the explanation of an constant class was like follows.. "If there's no constructor in a class, the try to instantiate constant object of that class would issue an compiler error.." But, the code as follows doen't issue no compiler error.. Please tell me what was that I misunderstood. #include <iostream> using namespace std; class MyClass { public: void myPrint() const ; }; void MyClass::myPrint() const { cout << "Hello~~" << endl; } int main() { const MyClass obj; obj.myPrint(); return 0; }

9th Nov 2016, 5:01 AM
Sang Yoon Lee
Sang Yoon Lee - avatar
1 Answer
+ 1
consider this class: #include <iostream> using namespace std; class MyClass { int no; public: void myPrint() const ; MyClass(int a){ no = a; } }; void MyClass::myPrint() const { cout << "Hello~~" << endl; cout<<no; } int main() { const MyClass obj(2); obj.myPrint(); return 0; } the statement means that you can instantiate an object only through constructor. if you would like to change the value of data member (or initialise) through some other function, it would show error as its a constant object.i.e. read only object. In this class, if you put the statement no = 2; in myPrint() function, it will show error since you are changing constant object.
9th Nov 2016, 6:44 AM
kamal joshi
kamal joshi - avatar