how to make a class not inheritable in c++? It is an c++ interview question ans generally asked to the less experience c++ programmer. In the old version of c++ standard making a c++ class is somewhat a difficult task ( specially for beginners ) , but c++ 11 provides final key word to make a class final. Final classes are not inheritable.

how to make a class not inheritable in c++11

  • It is to prevent a class from being inherited. So below code will not compile. it will error out “error: cannot derive from ‘final’ base ‘Base’ in derived type ‘Derived’.
#include<iostream>
using namespace std;

class Base final { };

class Derived: Base {  // error cannot inherit class Base
};
int main() {
	return 0;
}
  • It is also used to mark a virtual function so as to prevent it from being overridden in the derived classes.

how to make a class not inheritable in c++98

Let us see below example.

#include<iostream>
using namespace std;

class FinalClass;

class Flock {
private:
	Flock() {
	}
	~Flock() {
	}
	friend class FinalClass;
};

class FinalClass: public virtual Flock {

};

class DerivedClas: public FinalClass {

};

int main() {
	FinalClass o; // no error
	DerivedClas obj; // error
	return 0;
}

Think How it Works?

Ref:

http://stackoverflow.com/questions/1366441/final-class-in-c



Related Contents to follow