How to create a class that cannot be inherited by other classes?

Can anyone tell how to create a class so that it cannot be inherited by other classes.

class A {
  public :
          int a;
          int b;
};

class B : class A {
   public :
           int c;
};

in the above program, I do not want other classes to be inherited by class B

+4
source share
2 answers

Note the class final(since C ++ 11):

class A final {
public :
    int a;
    int b;
};
+13
source

If you are using C ++ 11 or later, you can use the keyword finalas mentioned in another answer. And this should be the recommended solution.

, ++ 03/++ 98, private factory.

class A {
private:
    A(int i, int j) : a(i), b(j) {}
    // other constructors.

    friend A* create_A(int i, int j);
    // maybe other factory methods.
};

A* create_A(int i, int j) {
    return new A(i, j);
}
// maybe other factory methods.
+5

Source: https://habr.com/ru/post/1650789/


All Articles