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
  • 237
  • 2
  • 14

2 Answers2

13

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

class A final {
public :
    int a;
    int b;
};
Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
Jarod42
  • 190,553
  • 13
  • 166
  • 271
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
  • 17,274
  • 3
  • 30
  • 41