C++ Public access specifier instead of Private – What is bad?

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?

If you want to know access specifiers in C++ programming,  read another interview question on: access specifiers in C++ and use of C++ access specifiers .

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.

class Insurance{
public:	
	int year;
	float sum;
public:
	Insurance(){
		this->sum =5.0;
	}
	float getSum(){
		return sum;
	}
};

class TaxCalculator{

	Insurance obj;
public:
	TaxCalculator(){
		obj.sum = 100;
	}
	float getTax(){
		float tax = obj.getSum()*10/100;		
		return tax;
	}

};


int main(){
	//Access to public functions 
	TaxCalculator tc;
	cout<< "Tax="<<tc.getTax();
	
	return 0;
}


Related Posts