Interview Question: A class is having private data members and that is by design and expected. Question is, if we write C++ public access specifier instead of private for that data members then what issue we can face in a C++ program?
Answer: Wrongly placed specifiers may create a huge pain in maintenance or finding bugs for changed behavior of a large C++ project.
In a simple program it may not be noticeable. But, in a large program where tons of classes and tons of functions are there, it may be difficult to find issues. So, we need to keep focus when using access specifiers in C++ software projects.
Let’s take a simple C++ code example . If we use public access specifier instead of private for data members in a class, compiler is not going to complain and programs work fine. However, it may lead to an issue unknowingly.
In below C++ program, there is a class called Insurance and it contains a data member “float sum” and the value of “sum” has been initialize to 5.0. There is another class TaxCalculator which is using the value of sum variable to calculate the tax with formula float tax = obj.getSum()*10/100;. Expected answer for this program is 0.5.
But assume, by mistake, if some programmer changed its value in TaxCalculator class that is sum=100, may be to solve other problems. Then value of tax will become 10 that was not expected. So, we have to be careful with choosing access specifiers for members and functions.
obj.sum = 100;
float tax = obj.getSum()*10/100;
//Access to public functions