Disabling Functions in C++11 with the delete Specifier

Preventing Inheritance of Base Class Methods

In C++11, the = delete specifier provides a clean way to disable specific functions. This is particularly useful when you want to prevent a derived class from using certain member functions inherited from a base class.

Conisder a simple arithmetic class:

#include <iostream>

class BaseCalculator
{
public:
    int multiply(int x, int y) { return x * y; }
    int divide(int x, int y) { return x / y; }
};

class DerivedCalculator : public BaseCalculator
{
public:
    // Disable the inherited divide function
    int divide(int, int) = delete;
};

int main()
{
    BaseCalculator base;
    std::cout << "6 * 3 = " << base.multiply(6, 3) << std::endl;
    std::cout << "6 / 3 = " << base.divide(6, 3) << std::endl;

    DerivedCalculator derived;
    std::cout << "8 * 4 = " << derived.multiply(8, 4) << std::endl;
    
    // This line would cause a compilation error:
    // std::cout << "8 / 4 = " << derived.divide(8, 4) << std::endl;
    
    return 0;
}

When the = delete specifier is applied to the divide functon in DerivedCalculator, any attempt to call divide on a DerivedCalculator object results in a compile-time error.

Disabling the Copy Constructor

Another common use case is preventing objects from being copied. The copy constructor is implicitly generated by the compiler unless you explicitly delete it. Here's how to disable it:

#include <iostream>

class NonCopyable
{
public:
    NonCopyable(int val) : value(val) {}
    
    int getValue() const { return value; }
    
    // Explicitly delete the copy constructor
    NonCopyable(const NonCopyable&) = delete;

private:
    int value;
};

int main()
{
    NonCopyable obj1(42);
    std::cout << "Value: " << obj1.getValue() << std::endl;
    
    // This line would fail to compile:
    // NonCopyable obj2 = obj1;
    
    return 0;
}

After adding = delete to the copy constructor, any code attempting to copy a NonCopyable object will fail at compile time.

Summary

The = delete specifier can be applied to:

  • Inherited member functions from base classes that should not be accessible
  • Implicitly-generated special member functions (copy constructor, move constructor, copy assignment, move assignment)
  • Any other function that should be explicitly prohibited

This technique replaces older approaches like declaring functions as private without providing definitions, offering better error messages and clearer intent in the code.

Reference

Tags: C++11 delete specifier special member functions disable functions

Posted on Sat, 06 Jun 2026 17:58:11 +0000 by sbcwebs