4

Can anyone tell how to create class so that it can not be inherited by any other classes.

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

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

in above program i do not want to allow other classes to be inherited by class B

ssg
  • 247
  • 2
  • 15

2 Answers2

13

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

class A final {
public :
    int a;
    int b;
};
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jarod42
  • 203,559
  • 14
  • 181
  • 302
5

If you are using C++11 or later, you can use the final keyword, just as the other answer mentioned. And that should be the recommended solution.

However, if have to struggle with C++03 / C++98, you can make the class's constructors private, and create object of this class with a factory method or class.

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.
for_stack
  • 21,012
  • 4
  • 35
  • 48