Answer to Question #251331 in C++ for Asim

Question #251331

Make all the 

appropriate function constant. Include a constant data member called id of integer 

type. 

Create two object constant and non-constant. Assign values and display them. Also 

check what happens 

 If you try to modify private data member of an object from the definition of 

const function 

 If you try to modify the private data member of const object from the 

definition of non-constant function.


1
Expert's answer
2021-10-15T01:27:57-0400
#include <iostream>
using namespace std;
 
class Constant {
    int id;
 
public:
	int value;
    Constant(int v = 0) { id = v; }
    int getvalue() {return value;
	}
 
    int getid() const { return id; }
};
 
int main()
{
    Constant t(10);
    cout<<t.getid();
    return 0;
}


Any attempt to modify the private member variables of the object is disallowed as it will violate the constant-ness of the object.

compilation error will occur if you also try to modify private data member of constant object from definition of non-constant object. This is because every class method is a function that implicitly passes this as a parameter. When you declare a method as constant, that means that it will actually pass constant this to this function therefore it is both correct logically and syntactically not to call not constant methods from constant methods.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS