Sealed classes

How can we implement sealed classes in C++

Answer this question

Sealed classes

  • Unbroken73

    Than make it protected.

    If the constructor is protected or private no onw can create an object of this instance. Except a static function or you derive from it.

    class A
    {
       A() {}
    };

    void foo()
    {
       A instanceOfA;
    }

    Gives an error as expected!

  • Justin-M

    Hi,

    ThanksSmile. If we implement the class with private constructor, we can't inherit. But, it is giving Runtime error.Instead of that, i want to validate it in compilation time. is there any way

    kedar.

  • Pete Cotton

    You cannot protect a class against derivation. But you can protect the creation of the class, this is the idea.
    If the class can only be constructed by a factory (static function inside) nobody can derive it.

    class A
    {
    private:
       A() {}
    public:
       static A* Construct()   
       {
          return new A();
       }
    }

    void Foo()
    {
       A *pA = A::Construct();
       delete pA;
    }

    Nobody can create a derivied class of A!
    You can not protect anybody to do this:
    class B : public A
    {
    };

    But nobody can create the class B!
    The .NET languages have a keyword sealed. This is not available in native C++.
    HTH

  • anton pakhomov

    Hi martin,

    It doesn't make any difference. I want to control the user from extending my class at the compilation time.

    thanks,
    kedar

  • er824

    If you make all constructors private, then nothing can inherit from your class.  To still allow creation of objects, you need to add static methods that return instances of your class.


  • Sealed classes