Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Preventing a static method in base class from being called through derived class?

I have a Base class, and a Derived template that inherits from it. Both of these define a static method calculateSize() but with different method signatures. (Both are also instanced as objects; Base isn’t just an interface.)

class Base{
public:
    static size_t calculateSize(size_t payload); 
};

template<typename T>
class Derived : public Base{
public:
    // sloppy fixo to prevent Base::calc() from being called
    static size_t calculateSize(size_t){ assert(0); return calculateSize(); }  
    
    // correct method to call
    static size_t calculateSize();
};

The Base class’s version of this method would give a wrong answer if called for a Derived type, so I want to prevent it from accidentally being called through Derived::calculateSize(sz). How would this typically be accomplished? (I currently have a method with the same signature in Derived that asserts if called, this feels kinda hacky though…)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you have a calculateSize in the derived class, it will hide calculateSize in the base class, so you can simply just not have anything:

template<typename T>
class Derived : public Base {
public:
    static size_t calculateSize();
};

// Error: no function that takes an argument
size_t result = Derived<int>::calculateSize(1);

If you don’t have something to hide it or you want it to be more clear that you shouldn’t call it with the base classes signature, you can = delete it:

template<typename T>
class Derived : public Base {
public:
    // Explanatory comment here
    static size_t calculateSize(size_t) = delete;
    static size_t calculateSize();
};

// Error: trying to use deleted function
size_t result = Derived<int>::calculateSize(1);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading