Monday, December 30, 2024

Modify a private const variable from outside of class in c++

 Is it possible to modify a private const variable from outside the class in cpp? No it doesn't and it should not supposed to happen.

Unfortunately we can do this with pointer. How? Let's see the example:

#include <iostream>

class Test
{

    private:
    const int cval1 = 1;
    const int cval2 = 2;

    public: 
    void print()
    { 
        std::cout << "const value1 = " << cval1 << std::endl;
        std::cout << "const value2 = " << cval2 << std::endl;

    }    

};

int main()
{

    Test t;
    t.print();

    int * p = reinterpret_cast<int*>(&t);
   *p = 10; //modifying 1st integer
   *(p+1) = 20; //modifying 2nd integer

    std::cout << "After modification: " << std::endl;
    t.print();

    return 0;
}

No comments:

PC Magazine Tips and Solutions

PC World: Latest Technology News

PCWorld.com - Most Popular Downloads of the Week