Posted inInformation Technology

C++ — That Const Thing

lighthouse by sea against sky

Const is what makes C++ great. Const is what makes C++ too horrible to work with.

Developers who read those “Effective” books on C++ really screw the pooch. The developers working on the Qt library who hide everything anyone would want to override inside a “private” class only documented in the source file for the actual class and buried behind a macro passing most everything to it as const make the “screw the pooch” developers seem like they almost know what they are doing.

Honestly, if you are pulling shit like that in production code someone should definitely break both your thumbs if not worse. Libraries which pull shit like this are quickly being purged from the marketplace.

Academics vs. Production Coders

Academics think stuff like the above is “good and proper.” They’ve never written a line of production code in their lives. They definitely have never written production systems that went over 10 years without any modifications despite drastic changes to the business model. I have. It was written in the very early 1990s and is still in production today.

Not one of you writes code forward thinking and good enough to be placed in a private class.

Plymorphism

Nobody does. It is the pinnacle of arrogance to place the actual functionality inside a hidden private class leaving the exposed class as just a wrapper. You completely violate the fundamental tenant of OOP. Polymorphism.

When you bury the actual functionality inside a hidden private class passing const parameters you make it impossible to cleanly alter the class via inheritance. When you do it with methods that are not virtual one cannot even use override to fix your problem. If you are passing a base class pointer around you get the base class implementation, no matter what the actual object is. Doesn’t that suck?

Realities of Regulation

Academics and those who never studied actual Computer Science always design code like they are developing software for Walmart or some Internet startup. If there is a massive breach because they didn’t consider security, who cares? Nobody has gone to prison for that. The corporation will just buy N-months of credit monitoring and life will go on.

Those of us who have worked in the military contractor/black-ops/clearance required projects world and the FDA regulated world know that is not reality. In extreme cases you both go to prison and get barred from federal health programs. That’s right, she can get neither Medicare nor Medicaid. If she’s dead broke, when she gets sick she dies. You can even be banned from the industry like Pharma-bro.

Yes children, your OpenSource hack-on-the-fly code finds its way into these systems. It causes deaths, failures, and breaches because you would rather have fun hacking on the fly than apply actual Software Engineering. (Agile is not Software Engineering!)

Real Life Situation – LIMS

Yeah, I was going to give you a military example, but I can do it all in one. There is one class of software on which all lives depend: LIMS (Laboratory Information Management Systems) Every pharmaceutical and most defense contractors have them. Besides test composition/results and a bunch of other geekly things, one of the core assets held are MSDS (Material Safety Data Sheet) records. Many factories just have the paper sheets instead of a LIMS.

Prior to any chemical compound becoming the next Ozempic or a treatment for chemical/biological weapons exposure, it starts out in a lab. An MSDS must exist for it, but your access to any content other than the “Hazards” section is restricted by your clearance/employee role. Any chemical you can buy at a big box store, Pledge, Pine-Sol, ACT Flouride, etc. has a fully public MSDS. The antidotes for chemical/biological weapons will never have fully public MSDS.

How Do You Deal With It?

Take this LIMS market size report with a grain of salt. They are measuring “new sales” with that $2.3 Billion. Many companies rolled their own prior to canned packages becoming available. When I did a project in the 1980s for NutraSweet R&D they had purchased VG LIMS. The labs have changed hands, but odds are they are still running that system. Once you get a LIMS system you hire people to maintain it and run the thing until you can no longer find hardware to run it on. You need all of the lab history in case you are sued. Just look at the Bayer Round-Up trials. You need to keep that stuff forever. You also need to replicate point-in-time security levels. Yes, Dr. Susan has access to the information today in 2023, but did Dr. Susan have access to it on December 13th, 2013? (Leak/breach tracing requirement.)

Details

Let us say we are going to use the above TextEdit to display the various text blocks of an MSDS on the screen. Those who’ve never worked on the real world on production systems will try to put all of the security and editing in front of the setPlainText() call. That’s a security breach waiting to happen. Dictator Xi thanks you for providing China with access to all of this advanced Western Technology.

It needs to be inside of the setPlainText() call. That needs to make the determination, based on the user security level, which characters to replace with ASCII block characters. Your derived class needs to munge the data up based on the user. Why here? This is a one and done. No matter where you use the method it will call the security subroutine, blotting out what should not be visible for this user. Editing in front of the call means you have to do it and test it each and every place data is displayed. The fool who used const and buried all functionality in a hidden private class really screwed the pooch.

Some Const Basics

Many people think the above doesn’t belong in a technical discussion. Someone should warn them about thinking. You write software based on your life experience. When you are not formally trained and don’t have decades of experience, you make some damned short-sighted decisions. That’s where const is dangerous. People in the above group are telling you to use const everywhere. When you work on a library claiming to have some OpenSource aspect to it, you need to make good decisions not perpetuate design flaws.

Don’t use const to define your interface if there is a single use case that would need to modify the variable.

The code

/*
 * ConstThings.cpp
 *
 *  Created on: Jan 27, 2024
 *      Author: roland
 */
#include <iostream>
#include "config.h"
#include "mytriangle.h"

int main(int argc, char **argv) {
	std::cout << "ConstThings Example" << std::endl;
	std::cout << "Version " << ConstThings_VERSION_MAJOR << "." << ConstThings_VERSION_MINOR << std::endl;

	double a_base {3.678};
	double a_height {4.321};

	/*
	 * Normal non-const pointer to non-const variable
	 */

	double *a_ptr { &a_base };

	a_ptr = &a_height;			// can be re-assigned
	*a_ptr = 6.234;				// value of target variable can be re-assigned.

	std::cout << "value of a_height: " << a_height << std::endl;

	/*
	 * Placing const after the * means pointer is const.
	 * You can change the value at the destination but you cannot change
	 * where this pointer points.
	 */
	double* const c_ptr { &a_base };
	*c_ptr = 8.765;

	std::cout << "value of a_base: " << a_base << std::endl;


	/*
	 * Placing const before the pointer type declaration means a pointer to
	 * a const variable. A non-const pointer cannot point to a const variable.
	 *
	 * Yes, the standards committee really got this backwards!
	 *
	 * If you attempt to assign the address of either const double to d_ptr
	 * it would not compile because you would be casting away the const.
	 *
	 */
	const double b_base {8.32};		// d_ptr cannot point to either of these
	const double b_height {2.4};

	const double* b_ptr {&b_base};

	std::cout << "value *b_ptr: " << *b_ptr << std::endl;

	b_ptr = &b_height;
	std::cout << "value *b_ptr after re-pointing: " << *b_ptr << std::endl;

	/*
	 * a const pointer to a const value. All you can do is look at it.
	 */
	const double* const cant_change_nothing {&b_base};

	/*;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 * It's almost the same for objects
	 *;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
	 */

	MyTriangle mt( 3.0, 4.0);

	std::cout << "area of mt: " << mt.area() << std::endl;

	mt.setBase( 6.432);
	mt.setHeight( 2.345);

	std::cout << "area of mt after changes: " << mt.area() << std::endl;

	/*
	 * const pointer to non-const variable
	 */
	MyTriangle* const mt_ptr {&mt};

	mt_ptr->setBase(8.765);
	mt_ptr->setHeight(1.234);

	std::cout << "base: " << mt_ptr->base() << "  height: " << mt_ptr->height()
			<< "  area: " << mt_ptr->area() << std::endl;

	/*
	 * const pointer to a const variable
	 */
	const MyTriangle mt2(4,6);
	const MyTriangle* mt2_ptr {&mt2};

	std::cout << "mt2 base: " << mt2_ptr->base() << "  height: "
			<< mt2_ptr->height() << "  area: " << mt2_ptr->area() << std::endl;

	/*
	 * const pointer to const variable.
	 *
	 * You can only use methods which have been flagged as const!!!
	 *
	 * Try taking const off the methods that simply return values and this won't
	 * compile.
	 */
	const MyTriangle* const mt3_ptr {&mt2};

	std::cout << "mt3_ptr base: " << mt3_ptr->base()
			<< "  height: " << mt3_ptr->height()
			<< "  area:  " << mt3_ptr->area() << std::endl;
	return (0);
}
/*
 * mytriangle.cpp
 *
 *  Created on: Jan 27, 2024
 *      Author: roland
 */

#include "mytriangle.h"

MyTriangle::MyTriangle()
{
}

MyTriangle::MyTriangle(double base, double height) :
	m_base{ base } ,
	m_height{ height }
{
}

MyTriangle::~MyTriangle()
{
}

double MyTriangle::area() const
{
	return (ONE_HALF * m_base * m_height);
}

double MyTriangle::base() const
{
	return (m_base);
}

double MyTriangle::height() const
{
	return (m_height);
}

void MyTriangle::setHeight(double height)
{
	m_height = height;
}

void MyTriangle::setBase(double base)
{
	m_base = base;
}
/*
 * mytriangle.h
 *
 *  Created on: Jan 27, 2024
 *      Author: roland
 */

#ifndef MYTRIANGLE_H_
#define MYTRIANGLE_H_

class MyTriangle
{
public:
	MyTriangle();
	MyTriangle(double base, double height);
	virtual ~MyTriangle();

	const double ONE_HALF {0.5};

	double area() const;  // const allows methods to be used when object is const
	double base() const;
	double height() const;

	void setBase( double b);
	void setHeight( double h);
private:
	double m_base {0};
	double m_height {0};
};

#endif /* MYTRIANGLE_H_ */
cmake_minimum_required(VERSION 3.10)

# Set some basic project attributes
project (ConstThings
	VERSION 0.1
	DESCRIPTION "ConstThings example")

# This project will output an executable file
add_executable(${PROJECT_NAME} ConstThings.cpp mytriangle.cpp mytriangle.h)

# Create a simple configuration header
configure_file(config.h.in config.h)

# Include the configuration header in the build
target_include_directories(${PROJECT_NAME} PUBLIC "${PROJECT_BINARY_DIR}")

Output

ConstThings Example
Version 0.1
value of a_height: 6.234
value of a_base: 8.765
value *b_ptr: 8.32
value *b_ptr after re-pointing: 2.4
area of mt: 6
area of mt after changes: 7.54152
base: 8.765 height: 1.234 area: 5.40801
mt2 base: 4 height: 6 area: 12
mt3_ptr base: 4 height: 6 area: 12

Discussion

I used Mint Linux and Eclipse to create this code. Most of what you need to know is in the comments. That Agile mantra of “if the code is properly written it doesn’t need comments” is complete bullshit. Those losers don’t have systems that have been in production over 30 years, I do.

Just how many of you bother to put const at the end of your class methods which are little more than “getters?” Your classes won’t work if the instance is declared const and someone just wants to print the values.

When to Use Const

Only declare function/method parameters const if you can envision every use case. Most of you can’t. How many of you thought about having to have redacted text? The knee-jerk argument of “create your own class with a setSecuredText() method doesn’t get rid of the ticking time bomb. All it takes is one new developer and one new QA person for the setPlainText() method to get used in production because there is no way to hide it. Supreme Leader Putin thanks you for access to that information. Dictator Xi has now taken the formula for your wonder drug that cures all forms of cancer. China will be shipping it before your employer who actually paid for the research to discover it.

Like Agile before it, const has been hurled at bad programmers trying to make them more productive. Those “effective” and other C++ books tell you to make everything const, they are wrong. They are tying to stop the incompetent from shooting themselves in the foot and both kneecaps while introducing massive architectural flaws.

Go ahead. Try to inherit from that class adding a setSecuredText() call __and__ blocking the setPlainText(). You end up having to pull in a ton of their configuration macros, creating a shell wrapper class containing a hidden instance of this class, then pray it works with the next release.

Roland Hughes started his IT career in the early 1980s. He quickly became a consultant and president of Logikal Solutions, a software consulting firm specializing in OpenVMS application and C++/Qt touchscreen/embedded Linux development. Early in his career he became involved in what is now called cross platform development. Given the dearth of useful books on the subject he ventured into the world of professional author in 1995 writing the first of the "Zinc It!" book series for John Gordon Burke Publisher, Inc.

A decade later he released a massive (nearly 800 pages) tome "The Minimum You Need to Know to Be an OpenVMS Application Developer" which tried to encapsulate the essential skills gained over what was nearly a 20 year career at that point. From there "The Minimum You Need to Know" book series was born.

Three years later he wrote his first novel "Infinite Exposure" which got much notice from people involved in the banking and financial security worlds. Some of the attacks predicted in that book have since come to pass. While it was not originally intended to be a trilogy, it became the first book of "The Earth That Was" trilogy:
Infinite Exposure
Lesedi - The Greatest Lie Ever Told
John Smith - Last Known Survivor of the Microsoft Wars

When he is not consulting Roland Hughes posts about technology and sometimes politics on his blog. He also has regularly scheduled Sunday posts appearing on the Interesting Authors blog.

3 thoughts on “C++ — That Const Thing

  1. Something a little funky with the HTML on this article. The adverts from your books float a little bit to the left which obscures some of the right-hand text. It fails with all three popular browsers (MS-Edge, Chrome, Firefox)

  2. Thanks for the comment Neil. Sorry to take so long to reply. It wasn’t the article It was the fact nobody tests their WordPress themes before uploading them to the official download repo. I went back to an older theme and problem went away.

    Thanks again!

    Nice to know you are still on the sunny side of the daisies!

Leave a Reply