Hi,

Can anybody explain me how to create a sealed class on c++.

thanks in advance,
kedar

Dani AI

Generated

Short answer: if you can target C++11 or later, use the built-in final specifier. It is explicit, portable and gives a clear compile-time error when someone tries to derive.

class Sealed final {
public:
    Sealed() = default;
};

// error: class Derived : public Sealed { }; // base 'Sealed' is 'final'

For pre-C++11 compilers there are a few workarounds. The most common portable trick is to make all constructors private and provide a static factory; that prevents normal derivation because derived classes cannot call the base constructor. Be careful with special-member functions (copy/move/assignment): declare or delete them explicitly so the compiler does not create an unexpected public constructor. Another option on some toolchains is a vendor-specific language extension, but those are non-portable.

A note on 's macro approach: it does not reliably "seal" a class. Making a virtual base with a protected constructor still leaves derived classes able to access that protected constructor through the inheritance chain, so further derivation can compile. Also the example uses obsolete headers and other non-portable bits. As suggested, consider first whether you really need to forbid inheritance — often composition or documenting intended extension points is a better design.

Practical guidance: prefer final when available; if you must support older compilers, use the private-constructor + factory pattern and clearly document the reason. If only specific virtual functions should be closed for override, mark those functions final (or make them non-virtual) rather than sealing the entire class.

Recommended Answers

All 4 Replies

A start?

i know this solution using private constructor.

So, the user has to call the static method to create the new object. Is there anything better than this.

>Is there anything better than this.
No, not really. The question you should be asking yourself is why do you need this feature in the first place? Clicky.

#include <iostream.h>
#include <conio.h>

class SealedBase
{
protected:
    SealedBase()
    {
    }
};

#define Sealed private virtual SealedBase 

class Penguin : Sealed
{
};

class BigZ : Penguin
{
};

void main()
 {
BigZ bigZ;//cannot create obj beacuse penguin is sealed
  clrscr();
  cout<<"Sample for selaed":
  getch();
  }
commented: 6 year bump, no code tags, void main rubbish for TurboC -4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.