ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.6 months ago (distributed domain, exempt) |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://en.wikipedia.org/wiki/Metaclass |
| Last Crawled | 2026-03-25 07:32:57 (16 days ago) |
| First Indexed | 2014-03-10 08:34:03 (12 years ago) |
| HTTP Status Code | 200 |
| Meta Title | Metaclass - Wikipedia |
| Meta Description | null |
| Meta Canonical | null |
| Boilerpipe Text | In
object-oriented programming
, a
metaclass
is a
class
whose
syntactic
definitions are used for the syntactic definition of the classes themselves. Unlike ordinary classes, which define the behaviors of objects, metaclasses specify the behaviors of classes and their instances. Not all object-oriented
programming languages
support the concept of metaclasses. For those that do, the extent of control metaclasses have over class behaviors varies. Metaclasses are often implemented by treating classes as
first-class citizens
, making a metaclass an object that creates and manages these classes. Each programming language adheres to its own
metaobject protocol
, which are the rules that determine interactions among objects, classes, and metaclasses.
[
1
]
Metaclasses are utilized to automate code generation and to enhance framework development.
[
2
]
In
Python
, the builtin class
type
is a metaclass.
[
3
]
[
4
]
[
5
]
Consider this simple Python class:
class
Car
:
make
:
str
model
:
str
year
:
int
color
:
str
def
__init__
(
self
,
make
:
str
,
model
:
str
,
year
:
int
,
color
:
str
)
->
None
:
self
.
make
=
make
self
.
model
=
model
self
.
year
=
year
self
.
color
=
color
@property
def
description
(
self
)
->
str
:
"""
Return a description of this car.
"""
return
f
"
{
self
.
color
}
{
self
.
make
}
{
self
.
model
}
"
At run time,
Car
itself is an instance of
type
. The source code of the
Car
class, shown above, does not include such details as the size in bytes of
Car
objects, their binary layout in memory, how they are allocated, that the
__init__
method is automatically called each time a
Car
is created, and so on. These details come into play not only when a new
Car
object is created, but also each time any attribute of a
Car
is accessed. In languages without metaclasses, these details are defined by the language specification and can't be overridden. In Python, the metaclass -
type
- controls these details of
Car
's behavior. They can be overridden by using a different metaclass instead of
type
.
The above example contains some redundant code to do with the four attributes
make
,
model
,
year
, and
color
. It is possible to eliminate some of this redundancy using a custom metaclass. In Python, a metaclass is most easily defined as a subclass of
type
.
from
typing
import
Any
class
AttributeInitType
(
type
):
def
__call__
(
self
,
*
args
:
tuple
[
Any
],
**
kwargs
:
dict
[
str
,
Any
])
->
object
:
"""
Create a new instance.
"""
# First, create the object in the normal default way.
obj
:
object
=
type
.
__call__
(
self
,
*
args
)
# Additionally, set attributes on the new object.
for
name
,
value
in
kwargs
.
items
():
setattr
(
obj
,
name
,
value
)
# Return the new object.
return
obj
This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by
type
.
Now the class
Car
can be rewritten to use this metaclass. In Python 3 this is done by providing a "keyword argument"
metaclass
to the class definition:
class
Car
(
object
,
metaclass
=
AttributeInitType
):
@property
def
description
(
self
)
->
str
:
"""
Return a description of this car.
"""
return
" "
.
join
(
str
(
value
)
for
value
in
self
.
__dict__
.
values
())
The resulting object
Car
can be instantiated as usual, but can contain any number of keyword arguments:
new_car
:
Car
=
Car
(
make
=
'Toyota'
,
model
=
'Prius'
,
year
=
2005
,
color
=
'Green'
,
engine
=
'Hybrid'
)
The Smalltalk-80 metaclass hierarchy as a UML diagram
Diagram of the inheritance and instance relationships between classes and metaclasses in Smalltalk
In
Smalltalk
, everything is an
object
. Additionally, Smalltalk is a
class based
system, which means that every object has a class that defines the structure of that object (i.e. the instance variables the object has) and the messages an object understands. Together this implies that a class in Smalltalk is an object and that, therefore a class needs to be an instance of a class (called metaclass).
As an example, a car object
c
is an instance of the class
Car
. In turn, the class
Car
is again an object and as such an instance of the metaclass of
Car
called
Car class
. Note the blank in the name of the metaclass. The name of the metaclass is the Smalltalk expression that, when evaluated, results in the metaclass object. Thus evaluating
Car class
results in the metaclass object for
Car
whose name is
Car class
(one can confirm this by evaluating
Car class name
which returns the name of the metaclass of
Car
.)
Class methods
actually belong to the metaclass, just as instance methods actually belong to the class. When a message is sent to the object
2
, the search for the method starts in
Integer
. If it is not found it proceeds up the superclass chain, stopping at Object whether it is found or not.
When a message is sent to
Integer
the search for the method starts in
Integer class
and proceeds up the superclass chain to
Object class
. Note that, so far, the metaclass inheritance chain exactly follows that of the class inheritance chain. But the metaclass chain extends further because
Object class
is the subclass of
Class
. All metaclasses are subclasses of Class.
In early Smalltalks, there was only one metaclass called
Class
. This implied that the
methods
all classes have were the same, in particular the method to create new objects, i.e.,
new
. To allow classes to have their own methods and their own instance variables (called class instance variables and should not be confused with
class variables
), Smalltalk-80 introduced for each class
C
their own metaclass
C class
. This means that each metaclass is effectively a
singleton
class.
Since there is no requirement that metaclasses behave differently from each other, all metaclasses are instances of only one class called
Metaclass
. The metaclass of
Metaclass
is called
Metaclass class
which again is an instance of class
Metaclass
.
In Smalltalk-80, every class (except
Object
) has a
superclass
. The
abstract superclass
of all metaclasses is
Class
, which describes the general nature of classes.
The superclass hierarchy for metaclasses parallels that for classes, except for class
Object
. ALL metaclasses are subclasses of
Class
, therefore:
Object class superclass == Class.
Like
conjoined twins
, classes and metaclasses are born together.
Metaclass
has an instance variable
thisClass
, which points to its conjoined class.
Note that the usual Smalltalk
class browser
does not show metaclasses as separate classes. Instead the class browser allows to edit the class together with its metaclass at the same time.
The names of classes in the metaclass hierarchy are easily confused with the concepts of the same name. For instance:
Object
is the base class that provides common methods for all objects; "an object" is an integer, or a widget, or a
Car
, etc.
Class
is the base of the metaclasses that provides common methods for all classes (though it is not a metaclass itself); "a class" is something like
Integer
, or
Widget
, or
Car
, etc.
Metaclass
provides common methods for all metaclasses.
Four classes provide the facilities to describe new classes. Their
inheritance hierarchy
(from Object), and the main facilities they provide are:
Object - default behavior common to all objects, like class access
Behavior - minimum
state
for
compiling
methods and creating/running objects
ClassDescription (
abstract class
) - class/variable naming, comments
Class - similar, more comprehensive, facilities to superclasses
Metaclass - initializing class variables, instance creation messages
Ruby purifies the Smalltalk-80 concept of metaclasses by introducing
eigenclasses
,
removing the
Metaclass
class,
and (un)redefining the class-of map.
The change can be schematized as follows:
[
6
]
Smalltalk-80
Classes
Implicit
metaclasses
Terminal
objects
→
Ruby
Classes
Eigenclasses of
classes
Eigenclasses
of
eigenclasses
Terminal
objects
Eigenclasses of
terminal objects
Note in particular the correspondence between Smalltalk's implicit metaclasses and Ruby's eigenclasses of classes.
The Ruby eigenclass model makes the concept of implicit metaclasses fully uniform: every object
x
has its own meta-object, called the
eigenclass
of
x
, which is one meta-level higher than
x
. The "higher order" eigenclasses usually exist purely conceptually – they do not contain any methods or store any (other) data in most Ruby programs.
[
7
]
The following diagrams show a sample core structure of Smalltalk-80 and Ruby in comparison.
[
8
]
In both languages, the structure consists of a built-in part which contains the circular objects (i.e. objects that appear in a cycle formed by a combination of blue or green links) and a user-part which has four explicit objects: classes
A
and
B
and terminal objects
u
and
v
.
Green links show the child→parent relation of inheritance (with the implicit upward direction), blue links show the complementary member→container relation of instantiation (a blue link from
x
points to the least actual container of
x
that is the start point for the method lookup when a method is invoked on
x
). Gray nodes display the eigenclasses (resp. implicit metaclasses in the case of Smalltalk-80).
The diagram on the right also provides a picture of
lazy evaluation
of eigenclasses in Ruby. The
v
object can have its eigenclass evaluated (allocated) as a consequence of adding
singleton methods
to
v
.
According to the Ruby's introspection method named
class
,
the class of every class (and of every eigenclass) is
constantly the
Class
class (denoted by
c
in the diagram).
Class
, and
Struct
are the only classes that have classes as instances.
[
9
]
[
disputed
–
discuss
]
Subclassing of
Class
is disallowed.
Following the standard definition of metaclasses we can conclude that
Class
and
Struct
are the only metaclasses in Ruby.
This seems to contradict the correspondence between Ruby and Smalltalk,
since in Smalltalk-80, every class has its own metaclass.
The discrepancy is based on the disagreement between
the
class
introspection method in Ruby and Smalltalk. While the map
x ↦ x.
class
coincides on terminal objects, it differs in the restriction to classes. As already mentioned above, for a class
x
, the Ruby expression
x
.class
evaluates constantly to
Class
. In Smalltalk-80, if
x
is a class then the expression
x
class
corresponds
to the Ruby's
x
.singleton_class
– which evaluates to the eigenclass of
x
.
Diagram of the inheritance and instance relationships between classes and metaclasses in Objective-C. Note that Objective-C has multiple root classes; each root class would have a separate hierarchy. This diagram only shows the hierarchy for an example root class NSObject. Each other root class would have a similar hierarchy.
Metaclasses in Objective-C are almost the same as those in Smalltalk-80—not surprising since Objective-C borrows a lot from Smalltalk. Like Smalltalk, in Objective-C, the instance variables and methods are defined by an object's class. A class is an object, hence it is an instance of a metaclass.
Like Smalltalk, in Objective-C, class methods are simply methods called on the class object, hence a class's class methods must be defined as instance methods in its metaclass. Because different classes can have different sets of class methods, each class must have its own separate metaclass. Classes and metaclasses are always created as a pair: the runtime has functions
objc_allocateClassPair()
and
objc_registerClassPair()
to create and register class-metaclass pairs, respectively.
There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type
Class
(similar to the type
id
being used for a pointer to any object).
Because class methods are inherited through inheritance, like Smalltalk, metaclasses must follow an inheritance scheme paralleling that of classes (e.g. if class A's parent class is class B, then A's metaclass's parent class is B's metaclass), except that of the root class.
Unlike Smalltalk, the metaclass of the root class inherits from the root class (usually
NSObject
using the
Cocoa
framework) itself. This ensures that all class objects are ultimately instances of the root class, so that you can use the instance methods of the root class, usually useful utility methods for objects, on class objects themselves.
Since metaclass objects do not behave differently (you cannot add class methods for a metaclass, so metaclass objects all have the same methods), they are all instances of the same class—the metaclass of the root class (unlike Smalltalk). Thus, the metaclass of the root class is an instance of itself. The reason for this is that all metaclasses inherit from root class; hence, they must inherit the class methods of the root class.
[
10
]
Herb Sutter
of the ISO C++ Committee, first proposed the inclusion of metaclasses to C++ for
C++20
using
C++17
features.
[
11
]
With the adoption of
reflection
in
C++26
, this paper was revised.
[
12
]
Its primary goal is to expand C++ abstraction beyond defined vocabulary (
class
,
struct
,
union
,
enum
, etc.) to allow adoptable vocabulary (such as
interface
,
value
), for the purpose of a more liberal approach to programming free of rule-memorisation. This feature would also allow non-standard features (such as
interface
s
) to be expressed as core features within libraries, and eliminate the necessity of specialised compilers (such as
Qt moc
,
C++/CX
, etc.) to express specific information using standardised features.
Using
code injection
(another proposed addition to C++ reflection which would add token sequence injection into source code)
[
13
]
, one would be able to create a Java/C# style "
interface
" using a
consteval
function:
import
std
;
using
std
::
string
;
using
std
::
string_view
;
using
std
::
meta
::
info
;
[[
nodiscard
]]
consteval
info
makeInterfaceFunctions
(
info
proto
)
noexcept
{
info
ret
=
^^
{};
for
(
info
mem
:
std
::
meta
::
members_of
(
proto
))
{
if
(
std
::
meta
::
is_nonspecial_member_function
(
mem
))
{
ret
=
^^
{
\
tokens
(
ret
)
virtual
[
:
\
(
std
::
meta
::
return_type_of
(
mem
))
:
]
\
id
(
std
::
meta
::
identifier_of
(
mem
))
(
\
tokens
(
std
::
meta
::
parameter_list_of
(
mem
)))
=
0
;
};
}
else
if
(
std
::
meta
::
is_variable
(
mem
))
{
// Report a compile-time error (not yet a feature in C++)
}
}
return
ret
;
}
consteval
void
interface
(
info
proto
)
noexcept
{
string_view
name
=
std
::
meta
::
identifier_of
(
proto
);
std
::
meta
::
queue_injection
(
^^
{
class
\
id
(
name
)
{
public
:
// make interface functions
\
tokens
(
makeInterfaceFunctions
(
proto
))
// the destructor
virtual
~
\
id
(
name
)()
=
default
;
// the constructor
\
id
(
name
)()
=
default
;
// delete the copy constructor
\
id
(
name
)(
\
id
(
name
)
const
&
)
=
delete
;
// delete the copy assignment operator
void
operator
=
(
\
id
(
name
)
const
&
)
=
delete
;
};
});
}
// use "interface":
class
(
interface
)
IFoo
{
int
f
();
void
g
(
string
s
);
};
It would also be possible to apply multiple metaclass types. For example, for metaclasses
x
and
y
, one could write
class
(
x
,
y
)
MyClass
{
/* ... */
};
.
The paper proposes that this allows for abstractions to greatly decrease boilerplate by producing generated functions and customisable defaults, semantics, and constraints. It further abolishes the need to create new language feature proposals by allowing such features to be expressed using metaclass features.
Support in languages and tools
[
edit
]
The following are some of the most prominent
programming languages
that support metaclasses.
Common Lisp
, via
CLOS
Delphi
and other versions of
Object Pascal
influenced by it
Groovy
Objective-C
ooRexx
Python
Perl
, via the metaclass pragma, as well as
Moose
Ruby
Smalltalk
Some less widespread languages that support metaclasses include
OpenJava
[
14
]
,
OpenC++
[
15
]
[
16
]
,
OpenAda
,
CorbaScript
,
ObjVLisp
,
Object-Z
,
MODEL-K
,
XOTcl
, and
MELDC
. Several of these languages date from the early 1990s and are of academic interest.
[
17
]
Java
features
java.lang.Class<T>
for
introspection
, similar to metaclasses, but are not actually metaclasses.
Logtalk
, an object-oriented extension of
Prolog
, also supports metaclasses.
Resource Description Framework
(RDF) and
Unified Modeling Language
(UML) both support metaclasses.
Metaclasses were a proposed for a possible inclusion in future version of
C++
, but currently is not an included feature.
[
11
]
Metamodel
Metaprogramming
Metaobject
Kind (type theory)
Reflection
Dynamism
Adapter pattern
Metaclass (Semantic Web)
^
Forman, Ira R.; Danforth, Scott (1999).
Putting Metaclasses to Work
. Addison-Wesley.
ISBN
0-201-43305-2
.
^
AloorRavi, Sulekha (2022).
Metaprogramming with Python
. Birmingham: Packt Publishing.
^
IBM Metaclass programming in Python, parts
1
Archived
3 September 2008 at the
Wayback Machine
,
2
Archived
23 August 2008 at the
Wayback Machine
and
3
Archived
21 March 2009 at the
Wayback Machine
^
Artima Forum: Metaclasses in Python 3.0
(part 1 of 2)
Archived
24 September 2020 at the
Wayback Machine
(part 2 of 2)
Archived
9 April 2016 at the
Wayback Machine
^
Mertz, David.
"A Primer on Python Metaclass Programming"
.
ONLamp
. Archived from
the original
on 30 April 2003
. Retrieved
28 June
2006
.
^
"The Ruby Object Model: Comparison with Smalltalk-80"
.
Archived
from the original on 17 January 2020
. Retrieved
10 February
2012
.
^
Perrotta, Paolo (2010).
Metaprogramming Ruby
. Pragmatic Bookshelf.
ISBN
978-1-934356-47-0
. Archived from
the original
on 9 June 2016
. Retrieved
21 November
2013
.
^
"Object Membership: The Core Structure of Object Technology"
.
Archived
from the original on 6 May 2021
. Retrieved
24 August
2012
.
^
"Struct"
.
Archived
from the original on 3 May 2025
. Retrieved
28 April
2025
.
^
"What is a meta-class in Objective-C?"
.
Cocoa with Love
. 17 January 2010.
Archived
from the original on 6 August 2011
. Retrieved
22 July
2011
.
^
a
b
Sutter, Herb
(18 June 2017).
"P0707 R0 - Metaclasses"
(PDF)
.
open-std.org
. WG21.
Archived
(PDF)
from the original on 11 November 2020
. Retrieved
8 August
2018
.
^
Sutter, Herb
(12 October 2024).
"Declarative class authoring using consteval functions + reflection + generation (aka: Metaclasses for generative C++)"
(PDF)
.
open-std.org
. WG21
. Retrieved
14 December
2025
.
^
Andrei Alexandrescu, Barry Rezvin, Daveed Vandevoorde (16 July 2024).
"Code Injection with Token Sequences"
.
open-std.org
. WG21.
{{
cite web
}}
: CS1 maint: multiple names: authors list (
link
)
^
Michiaki Tatsubori (14 October 2007).
"OJ: An Extensible Java"
.
csg.ci.i.u-tokyo.ac.jp
. University of Tokyo. Archived from
the original
on 13 August 2014.
^
Shigeru Chiba (14 October 2007).
"OpenC++ Home Page"
.
csg.ci.i.u-tokyo.ac.jp
. University of Tokyo. Archived from
the original
on 21 August 2014.
^
Shigeru Chiba.
"Welcome to OpenC++"
.
opencxx.sourceforge.net
. University of Tokyo
. Retrieved
10 December
2025
.
^
"An implementation of mixins in Java using metaclasses"
(PDF)
. Archived from
the original
(PDF)
on 16 October 2007
. Retrieved
27 November
2007
.
What Is a Metaclass? |
| Markdown | [Jump to content](https://en.wikipedia.org/wiki/Metaclass#bodyContent)
Main menu
Main menu
move to sidebar
hide
Navigation
- [Main page](https://en.wikipedia.org/wiki/Main_Page "Visit the main page [z]")
- [Contents](https://en.wikipedia.org/wiki/Wikipedia:Contents "Guides to browsing Wikipedia")
- [Current events](https://en.wikipedia.org/wiki/Portal:Current_events "Articles related to current events")
- [Random article](https://en.wikipedia.org/wiki/Special:Random "Visit a randomly selected article [x]")
- [About Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:About "Learn about Wikipedia and how it works")
- [Contact us](https://en.wikipedia.org/wiki/Wikipedia:Contact_us "How to contact Wikipedia")
Contribute
- [Help](https://en.wikipedia.org/wiki/Help:Contents "Guidance on how to use and edit Wikipedia")
- [Learn to edit](https://en.wikipedia.org/wiki/Help:Introduction "Learn how to edit Wikipedia")
- [Community portal](https://en.wikipedia.org/wiki/Wikipedia:Community_portal "The hub for editors")
- [Recent changes](https://en.wikipedia.org/wiki/Special:RecentChanges "A list of recent changes to Wikipedia [r]")
- [Upload file](https://en.wikipedia.org/wiki/Wikipedia:File_upload_wizard "Add images or other media for use on Wikipedia")
- [Special pages](https://en.wikipedia.org/wiki/Special:SpecialPages "A list of all special pages [q]")
[  ](https://en.wikipedia.org/wiki/Main_Page)
[Search](https://en.wikipedia.org/wiki/Special:Search "Search Wikipedia [f]")
Appearance
- [Donate](https://donate.wikimedia.org/?wmf_source=donate&wmf_medium=sidebar&wmf_campaign=en.wikipedia.org&uselang=en)
- [Create account](https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Metaclass "You are encouraged to create an account and log in; however, it is not mandatory")
- [Log in](https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Metaclass "You're encouraged to log in; however, it's not mandatory. [o]")
Personal tools
- [Donate](https://donate.wikimedia.org/?wmf_source=donate&wmf_medium=sidebar&wmf_campaign=en.wikipedia.org&uselang=en)
- [Create account](https://en.wikipedia.org/w/index.php?title=Special:CreateAccount&returnto=Metaclass "You are encouraged to create an account and log in; however, it is not mandatory")
- [Log in](https://en.wikipedia.org/w/index.php?title=Special:UserLogin&returnto=Metaclass "You're encouraged to log in; however, it's not mandatory. [o]")
## Contents
move to sidebar
hide
- [(Top)](https://en.wikipedia.org/wiki/Metaclass)
- [1 Python example](https://en.wikipedia.org/wiki/Metaclass#Python_example)
- [2 In Smalltalk-80](https://en.wikipedia.org/wiki/Metaclass#In_Smalltalk-80)
- [3 In Ruby](https://en.wikipedia.org/wiki/Metaclass#In_Ruby)
- [4 In Objective-C](https://en.wikipedia.org/wiki/Metaclass#In_Objective-C)
- [5 C++ proposal](https://en.wikipedia.org/wiki/Metaclass#C++_proposal)
- [6 Support in languages and tools](https://en.wikipedia.org/wiki/Metaclass#Support_in_languages_and_tools)
- [7 See also](https://en.wikipedia.org/wiki/Metaclass#See_also)
- [8 References](https://en.wikipedia.org/wiki/Metaclass#References)
- [9 External links](https://en.wikipedia.org/wiki/Metaclass#External_links)
Toggle the table of contents
# Metaclass
12 languages
- [العربية](https://ar.wikipedia.org/wiki/%D8%B5%D9%86%D9%81_%D8%B9%D9%84%D9%88%D9%8A "صنف علوي – Arabic")
- [Deutsch](https://de.wikipedia.org/wiki/Metaklasse "Metaklasse – German")
- [Español](https://es.wikipedia.org/wiki/Metaclase "Metaclase – Spanish")
- [Français](https://fr.wikipedia.org/wiki/M%C3%A9taclasse "Métaclasse – French")
- [Italiano](https://it.wikipedia.org/wiki/Metaclasse "Metaclasse – Italian")
- [日本語](https://ja.wikipedia.org/wiki/%E3%83%A1%E3%82%BF%E3%82%AF%E3%83%A9%E3%82%B9 "メタクラス – Japanese")
- [한국어](https://ko.wikipedia.org/wiki/%EB%A9%94%ED%83%80%ED%81%B4%EB%9E%98%EC%8A%A4 "메타클래스 – Korean")
- [Português](https://pt.wikipedia.org/wiki/Metaclasse "Metaclasse – Portuguese")
- [Русский](https://ru.wikipedia.org/wiki/%D0%9C%D0%B5%D1%82%D0%B0%D0%BA%D0%BB%D0%B0%D1%81%D1%81 "Метакласс – Russian")
- [Tiếng Việt](https://vi.wikipedia.org/wiki/Si%C3%AAu_l%E1%BB%9Bp "Siêu lớp – Vietnamese")
- [粵語](https://zh-yue.wikipedia.org/wiki/%E5%85%83%E9%A1%9E%E5%88%A5 "元類別 – Cantonese")
- [中文](https://zh.wikipedia.org/wiki/%E5%85%83%E7%B1%BB "元类 – Chinese")
[Edit links](https://www.wikidata.org/wiki/Special:EntityPage/Q1924819#sitelinks-wikipedia "Edit interlanguage links")
- [Article](https://en.wikipedia.org/wiki/Metaclass "View the content page [c]")
- [Talk](https://en.wikipedia.org/wiki/Talk:Metaclass "Discuss improvements to the content page [t]")
English
- [Read](https://en.wikipedia.org/wiki/Metaclass)
- [Edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit "Edit this page [e]")
- [View history](https://en.wikipedia.org/w/index.php?title=Metaclass&action=history "Past revisions of this page [h]")
Tools
Tools
move to sidebar
hide
Actions
- [Read](https://en.wikipedia.org/wiki/Metaclass)
- [Edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit "Edit this page [e]")
- [View history](https://en.wikipedia.org/w/index.php?title=Metaclass&action=history)
General
- [What links here](https://en.wikipedia.org/wiki/Special:WhatLinksHere/Metaclass "List of all English Wikipedia pages containing links to this page [j]")
- [Related changes](https://en.wikipedia.org/wiki/Special:RecentChangesLinked/Metaclass "Recent changes in pages linked from this page [k]")
- [Upload file](https://en.wikipedia.org/wiki/Wikipedia:File_Upload_Wizard "Upload files [u]")
- [Permanent link](https://en.wikipedia.org/w/index.php?title=Metaclass&oldid=1327572642 "Permanent link to this revision of this page")
- [Page information](https://en.wikipedia.org/w/index.php?title=Metaclass&action=info "More information about this page")
- [Cite this page](https://en.wikipedia.org/w/index.php?title=Special:CiteThisPage&page=Metaclass&id=1327572642&wpFormIdentifier=titleform "Information on how to cite this page")
- [Get shortened URL](https://en.wikipedia.org/w/index.php?title=Special:UrlShortener&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FMetaclass)
Print/export
- [Download as PDF](https://en.wikipedia.org/w/index.php?title=Special:DownloadAsPdf&page=Metaclass&action=show-download-screen "Download this page as a PDF file")
- [Printable version](https://en.wikipedia.org/w/index.php?title=Metaclass&printable=yes "Printable version of this page [p]")
In other projects
- [Wikidata item](https://www.wikidata.org/wiki/Special:EntityPage/Q1924819 "Structured data on this page hosted by Wikidata [g]")
Appearance
move to sidebar
hide
From Wikipedia, the free encyclopedia
Class that describes common behavior for classes
| | |
|---|---|
|  | |
| | |
|  | This article **may contain [original research](https://en.wikipedia.org/wiki/Wikipedia:No_original_research "Wikipedia:No original research")**. Please [improve it](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit) by [verifying](https://en.wikipedia.org/wiki/Wikipedia:Verifiability "Wikipedia:Verifiability") the claims made and adding [inline citations](https://en.wikipedia.org/wiki/Wikipedia:Citing_sources#Inline_citations "Wikipedia:Citing sources"). Statements consisting only of original research should be removed. *(September 2013)* *([Learn how and when to remove this message](https://en.wikipedia.org/wiki/Help:Maintenance_template_removal "Help:Maintenance template removal"))* |
| | |
| [](https://en.wikipedia.org/wiki/File:Question_book-new.svg) | This article **needs additional citations for [verification](https://en.wikipedia.org/wiki/Wikipedia:Verifiability "Wikipedia:Verifiability")**. Please help [improve this article](https://en.wikipedia.org/wiki/Special:EditPage/Metaclass "Special:EditPage/Metaclass") by [adding citations to reliable sources](https://en.wikipedia.org/wiki/Help:Referencing_for_beginners "Help:Referencing for beginners"). Unsourced material may be challenged and removed. *Find sources:* ["Metaclass"](https://www.google.com/search?as_eq=wikipedia&q=%22Metaclass%22) – [news](https://www.google.com/search?tbm=nws&q=%22Metaclass%22+-wikipedia&tbs=ar:1) **·** [newspapers](https://www.google.com/search?&q=%22Metaclass%22&tbs=bkt:s&tbm=bks) **·** [books](https://www.google.com/search?tbs=bks:1&q=%22Metaclass%22+-wikipedia) **·** [scholar](https://scholar.google.com/scholar?q=%22Metaclass%22) **·** [JSTOR](https://www.jstor.org/action/doBasicSearch?Query=%22Metaclass%22&acc=on&wc=on) *(September 2013)* *([Learn how and when to remove this message](https://en.wikipedia.org/wiki/Help:Maintenance_template_removal "Help:Maintenance template removal"))* |
In [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming "Object-oriented programming"), a **metaclass** is a [class](https://en.wikipedia.org/wiki/Class_\(computer_science\) "Class (computer science)") whose [syntactic](https://en.wikipedia.org/wiki/Syntax_\(programming_language\) "Syntax (programming language)") definitions are used for the syntactic definition of the classes themselves. Unlike ordinary classes, which define the behaviors of objects, metaclasses specify the behaviors of classes and their instances. Not all object-oriented [programming languages](https://en.wikipedia.org/wiki/Programming_languages "Programming languages") support the concept of metaclasses. For those that do, the extent of control metaclasses have over class behaviors varies. Metaclasses are often implemented by treating classes as [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen "First-class citizen"), making a metaclass an object that creates and manages these classes. Each programming language adheres to its own [metaobject protocol](https://en.wikipedia.org/wiki/Metaobject_protocol "Metaobject protocol"), which are the rules that determine interactions among objects, classes, and metaclasses.[\[1\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-1) Metaclasses are utilized to automate code generation and to enhance framework development.[\[2\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-2)
## Python example
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=1 "Edit section: Python example")\]
In [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)"), the builtin class `type` is a metaclass.[\[3\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-3)[\[4\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-4)[\[5\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-5) Consider this simple Python class:
```
class Car:
make: str
model: str
year: int
color: str
def __init__(self, make: str, model: str, year: int, color: str) -> None:
self.make = make
self.model = model
self.year = year
self.color = color
@property
def description(self) -> str:
"""
Return a description of this car.
"""
return f"{self.color} {self.make} {self.model}"
```
At run time, `Car` itself is an instance of `type`. The source code of the `Car` class, shown above, does not include such details as the size in bytes of `Car` objects, their binary layout in memory, how they are allocated, that the `__init__` method is automatically called each time a `Car` is created, and so on. These details come into play not only when a new `Car` object is created, but also each time any attribute of a `Car` is accessed. In languages without metaclasses, these details are defined by the language specification and can't be overridden. In Python, the metaclass - `type` - controls these details of `Car`'s behavior. They can be overridden by using a different metaclass instead of `type`.
The above example contains some redundant code to do with the four attributes `make`, `model`, `year`, and `color`. It is possible to eliminate some of this redundancy using a custom metaclass. In Python, a metaclass is most easily defined as a subclass of `type`.
```
from typing import Any
class AttributeInitType(type):
def __call__(self, *args: tuple[Any], **kwargs: dict[str, Any]) -> object:
"""
Create a new instance.
"""
# First, create the object in the normal default way.
obj: object = type.__call__(self, *args)
# Additionally, set attributes on the new object.
for name, value in kwargs.items():
setattr(obj, name, value)
# Return the new object.
return obj
```
This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by `type`.
Now the class `Car` can be rewritten to use this metaclass. In Python 3 this is done by providing a "keyword argument" `metaclass` to the class definition:
```
class Car(object, metaclass=AttributeInitType):
@property
def description(self) -> str:
"""
Return a description of this car.
"""
return " ".join(str(value) for value in self.__dict__.values())
```
The resulting object `Car` can be instantiated as usual, but can contain any number of keyword arguments:
```
new_car: Car = Car(make='Toyota', model='Prius', year=2005, color='Green', engine='Hybrid')
```
## In Smalltalk-80
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=2 "Edit section: In Smalltalk-80")\]
| | |
|---|---|
| [](https://en.wikipedia.org/wiki/File:Question_book-new.svg) | This section **does not [cite](https://en.wikipedia.org/wiki/Wikipedia:Citing_sources "Wikipedia:Citing sources") any [sources](https://en.wikipedia.org/wiki/Wikipedia:Verifiability "Wikipedia:Verifiability")**. Please help [improve this section](https://en.wikipedia.org/wiki/Special:EditPage/Metaclass "Special:EditPage/Metaclass") by [adding citations to reliable sources](https://en.wikipedia.org/wiki/Help:Referencing_for_beginners "Help:Referencing for beginners"). Unsourced material may be challenged and [removed](https://en.wikipedia.org/wiki/Wikipedia:Verifiability#Burden_of_evidence "Wikipedia:Verifiability"). *(October 2013)* *([Learn how and when to remove this message](https://en.wikipedia.org/wiki/Help:Maintenance_template_removal "Help:Maintenance template removal"))* |
[](https://en.wikipedia.org/wiki/File:Smalltalk_80_metaclasses.svg)
The Smalltalk-80 metaclass hierarchy as a UML diagram
[](https://en.wikipedia.org/wiki/File:Smalltalk_metaclass.png)
Diagram of the inheritance and instance relationships between classes and metaclasses in Smalltalk
In [Smalltalk](https://en.wikipedia.org/wiki/Smalltalk "Smalltalk"), everything is an [object](https://en.wikipedia.org/wiki/Object_\(computer_science\) "Object (computer science)"). Additionally, Smalltalk is a [class based](https://en.wikipedia.org/wiki/Class-based_programming "Class-based programming") system, which means that every object has a class that defines the structure of that object (i.e. the instance variables the object has) and the messages an object understands. Together this implies that a class in Smalltalk is an object and that, therefore a class needs to be an instance of a class (called metaclass).
As an example, a car object `c` is an instance of the class `Car`. In turn, the class `Car` is again an object and as such an instance of the metaclass of `Car` called `Car class`. Note the blank in the name of the metaclass. The name of the metaclass is the Smalltalk expression that, when evaluated, results in the metaclass object. Thus evaluating `Car class` results in the metaclass object for `Car` whose name is `Car class` (one can confirm this by evaluating `Car class name` which returns the name of the metaclass of `Car`.)
[Class methods](https://en.wikipedia.org/wiki/Class_method "Class method") actually belong to the metaclass, just as instance methods actually belong to the class. When a message is sent to the object `2`, the search for the method starts in `Integer`. If it is not found it proceeds up the superclass chain, stopping at Object whether it is found or not.
When a message is sent to `Integer` the search for the method starts in `Integer class` and proceeds up the superclass chain to `Object class`. Note that, so far, the metaclass inheritance chain exactly follows that of the class inheritance chain. But the metaclass chain extends further because `Object class` is the subclass of `Class`. All metaclasses are subclasses of Class.
In early Smalltalks, there was only one metaclass called `Class`. This implied that the [methods](https://en.wikipedia.org/wiki/Method_\(computer_science\) "Method (computer science)") all classes have were the same, in particular the method to create new objects, i.e., `new`. To allow classes to have their own methods and their own instance variables (called class instance variables and should not be confused with [class variables](https://en.wikipedia.org/wiki/Class_variable "Class variable")), Smalltalk-80 introduced for each class `C` their own metaclass `C class`. This means that each metaclass is effectively a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern "Singleton pattern") class.
Since there is no requirement that metaclasses behave differently from each other, all metaclasses are instances of only one class called `Metaclass`. The metaclass of `Metaclass` is called `Metaclass class` which again is an instance of class `Metaclass`.
In Smalltalk-80, every class (except `Object`) has a [superclass](https://en.wikipedia.org/wiki/Superclass_\(computer_science\) "Superclass (computer science)"). The [abstract superclass](https://en.wikipedia.org/wiki/Abstract_superclass "Abstract superclass") of all metaclasses is `Class`, which describes the general nature of classes.
The superclass hierarchy for metaclasses parallels that for classes, except for class `Object`. ALL metaclasses are subclasses of `Class`, therefore:
- `Object class superclass == Class.`
Like [conjoined twins](https://en.wikipedia.org/wiki/Conjoined_twins "Conjoined twins"), classes and metaclasses are born together. `Metaclass` has an instance variable `thisClass`, which points to its conjoined class. Note that the usual Smalltalk [class browser](https://en.wikipedia.org/wiki/Class_browser "Class browser") does not show metaclasses as separate classes. Instead the class browser allows to edit the class together with its metaclass at the same time.
The names of classes in the metaclass hierarchy are easily confused with the concepts of the same name. For instance:
- `Object` is the base class that provides common methods for all objects; "an object" is an integer, or a widget, or a `Car`, etc.
- `Class` is the base of the metaclasses that provides common methods for all classes (though it is not a metaclass itself); "a class" is something like `Integer`, or `Widget`, or `Car`, etc.
- `Metaclass` provides common methods for all metaclasses.
Four classes provide the facilities to describe new classes. Their [inheritance hierarchy](https://en.wikipedia.org/wiki/Inheritance_hierarchy "Inheritance hierarchy") (from Object), and the main facilities they provide are:
Object - default behavior common to all objects, like class access
Behavior - minimum [state](https://en.wikipedia.org/wiki/State_\(computer_science\) "State (computer science)") for [compiling](https://en.wikipedia.org/wiki/Compiling "Compiling") methods and creating/running objects
ClassDescription ([abstract class](https://en.wikipedia.org/wiki/Abstract_class "Abstract class")) - class/variable naming, comments
Class - similar, more comprehensive, facilities to superclasses
Metaclass - initializing class variables, instance creation messages
## In Ruby
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=3 "Edit section: In Ruby")\]
Ruby purifies the Smalltalk-80 concept of metaclasses by introducing [eigenclasses](https://en.wiktionary.org/wiki/eigenclasses "wiktionary:eigenclasses"), removing the `Metaclass` class, and (un)redefining the class-of map. The change can be schematized as follows:[\[6\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-6)
| | | |
|---|---|---|
| | → | |
| | | |
| Classes | **Implicit metaclasses** | |
| Terminal objects | | |
| | | |
| Classes | **Eigenclasses of classes** | **Eigenclasses of eigenclasses** |
| Terminal objects | **Eigenclasses of terminal objects** | |
Note in particular the correspondence between Smalltalk's implicit metaclasses and Ruby's eigenclasses of classes. The Ruby eigenclass model makes the concept of implicit metaclasses fully uniform: every object *x* has its own meta-object, called the *eigenclass* of *x*, which is one meta-level higher than *x*. The "higher order" eigenclasses usually exist purely conceptually – they do not contain any methods or store any (other) data in most Ruby programs.[\[7\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-7)
The following diagrams show a sample core structure of Smalltalk-80 and Ruby in comparison.[\[8\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-8) In both languages, the structure consists of a built-in part which contains the circular objects (i.e. objects that appear in a cycle formed by a combination of blue or green links) and a user-part which has four explicit objects: classes `A` and `B` and terminal objects `u` and `v`. Green links show the child→parent relation of inheritance (with the implicit upward direction), blue links show the complementary member→container relation of instantiation (a blue link from *x* points to the least actual container of *x* that is the start point for the method lookup when a method is invoked on *x*). Gray nodes display the eigenclasses (resp. implicit metaclasses in the case of Smalltalk-80).
| | | |
|---|---|---|
| Smalltalk-80 | | Ruby |
| [](https://en.wikipedia.org/wiki/File:Smalltalk-metaclass-sample.svg "Implicit metaclasses in Smalltalk-80 - A sample structure") | | [](https://en.wikipedia.org/wiki/File:Ruby-metaclass-sample.svg "Eigenclasses in Ruby - A sample structure") |
The diagram on the right also provides a picture of [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation "Lazy evaluation") of eigenclasses in Ruby. The `v` object can have its eigenclass evaluated (allocated) as a consequence of adding *singleton methods* to `v`.
According to the Ruby's introspection method named `class`, the class of every class (and of every eigenclass) is constantly the `Class` class (denoted by `c` in the diagram). `Class`, and `Struct` are the only classes that have classes as instances.[\[9\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-9) \[*[disputed](https://en.wikipedia.org/wiki/Wikipedia:Disputed_statement "Wikipedia:Disputed statement") – [discuss](https://en.wikipedia.org/wiki/Talk:Metaclass#The_Struct_class_in_Ruby "Talk:Metaclass")*\] Subclassing of `Class` is disallowed. Following the standard definition of metaclasses we can conclude that `Class` and `Struct` are the only metaclasses in Ruby. This seems to contradict the correspondence between Ruby and Smalltalk, since in Smalltalk-80, every class has its own metaclass. The discrepancy is based on the disagreement between the `class` introspection method in Ruby and Smalltalk. While the map *x ↦ x.*`class` coincides on terminal objects, it differs in the restriction to classes. As already mentioned above, for a class `x`, the Ruby expression `x.class` evaluates constantly to `Class`. In Smalltalk-80, if `x` is a class then the expression `x class` corresponds to the Ruby's `x.singleton_class` – which evaluates to the eigenclass of `x`.
## In Objective-C
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=4 "Edit section: In Objective-C")\]
| | |
|---|---|
| [](https://en.wikipedia.org/wiki/File:Question_book-new.svg) | This section **needs additional citations for [verification](https://en.wikipedia.org/wiki/Wikipedia:Verifiability "Wikipedia:Verifiability")**. Please help [improve this article](https://en.wikipedia.org/wiki/Special:EditPage/Metaclass "Special:EditPage/Metaclass") by [adding citations to reliable sources](https://en.wikipedia.org/wiki/Help:Referencing_for_beginners "Help:Referencing for beginners") in this section. Unsourced material may be challenged and removed. *(October 2013)* *([Learn how and when to remove this message](https://en.wikipedia.org/wiki/Help:Maintenance_template_removal "Help:Maintenance template removal"))* |
| | |
|---|---|
|  | This section's **tone or style may not reflect the [encyclopedic tone](https://en.wikipedia.org/wiki/Wikipedia:Writing_better_articles#Tone "Wikipedia:Writing better articles") used on Wikipedia**. See Wikipedia's [guide to writing better articles](https://en.wikipedia.org/wiki/Wikipedia:Writing_better_articles#Tone "Wikipedia:Writing better articles") for suggestions. *(September 2013)* *([Learn how and when to remove this message](https://en.wikipedia.org/wiki/Help:Maintenance_template_removal "Help:Maintenance template removal"))* |
[](https://en.wikipedia.org/wiki/File:Objective-C_metaclass.png)
Diagram of the inheritance and instance relationships between classes and metaclasses in Objective-C. Note that Objective-C has multiple root classes; each root class would have a separate hierarchy. This diagram only shows the hierarchy for an example root class NSObject. Each other root class would have a similar hierarchy.
Metaclasses in Objective-C are almost the same as those in Smalltalk-80—not surprising since Objective-C borrows a lot from Smalltalk. Like Smalltalk, in Objective-C, the instance variables and methods are defined by an object's class. A class is an object, hence it is an instance of a metaclass.
Like Smalltalk, in Objective-C, class methods are simply methods called on the class object, hence a class's class methods must be defined as instance methods in its metaclass. Because different classes can have different sets of class methods, each class must have its own separate metaclass. Classes and metaclasses are always created as a pair: the runtime has functions `objc_allocateClassPair()` and `objc_registerClassPair()` to create and register class-metaclass pairs, respectively.
There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type `Class` (similar to the type `id` being used for a pointer to any object).
Because class methods are inherited through inheritance, like Smalltalk, metaclasses must follow an inheritance scheme paralleling that of classes (e.g. if class A's parent class is class B, then A's metaclass's parent class is B's metaclass), except that of the root class.
Unlike Smalltalk, the metaclass of the root class inherits from the root class (usually `NSObject` using the [Cocoa](https://en.wikipedia.org/wiki/Cocoa_\(API\) "Cocoa (API)") framework) itself. This ensures that all class objects are ultimately instances of the root class, so that you can use the instance methods of the root class, usually useful utility methods for objects, on class objects themselves.
Since metaclass objects do not behave differently (you cannot add class methods for a metaclass, so metaclass objects all have the same methods), they are all instances of the same class—the metaclass of the root class (unlike Smalltalk). Thus, the metaclass of the root class is an instance of itself. The reason for this is that all metaclasses inherit from root class; hence, they must inherit the class methods of the root class.[\[10\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-10)
## C++ proposal
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=5 "Edit section: C++ proposal")\]
[Herb Sutter](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") of the ISO C++ Committee, first proposed the inclusion of metaclasses to C++ for [C++20](https://en.wikipedia.org/wiki/C%2B%2B20 "C++20") using [C++17](https://en.wikipedia.org/wiki/C%2B%2B17 "C++17") features.[\[11\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses-11) With the adoption of [reflection](https://en.wikipedia.org/wiki/Reflective_programming "Reflective programming") in [C++26](https://en.wikipedia.org/wiki/C%2B%2B26 "C++26"), this paper was revised.[\[12\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses2-12)
Its primary goal is to expand C++ abstraction beyond defined vocabulary (`class`, `struct`, `union`, `enum`, etc.) to allow adoptable vocabulary (such as `interface`, `value`), for the purpose of a more liberal approach to programming free of rule-memorisation. This feature would also allow non-standard features (such as [`interface`s](https://en.wikipedia.org/wiki/Interface_\(object-oriented_programming\) "Interface (object-oriented programming)")) to be expressed as core features within libraries, and eliminate the necessity of specialised compilers (such as [Qt moc](https://en.wikipedia.org/wiki/Qt_\(software\)#Metaobject_compiler "Qt (software)"), [C++/CX](https://en.wikipedia.org/wiki/C%2B%2B/CX "C++/CX"), etc.) to express specific information using standardised features.
Using [code injection](https://en.wikipedia.org/wiki/Automatic_programming "Automatic programming") (another proposed addition to C++ reflection which would add token sequence injection into source code)[\[13\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-13), one would be able to create a Java/C\# style "`interface`" using a `consteval` function:
```
import std;
using std::string;
using std::string_view;
using std::meta::info;
[[nodiscard]]
consteval info makeInterfaceFunctions(info proto) noexcept {
info ret = ^^{};
for (info mem: std::meta::members_of(proto)) {
if (std::meta::is_nonspecial_member_function(mem)) {
ret = ^^{
\tokens(ret)
virtual [:\(std::meta::return_type_of(mem)):]
\id(std::meta::identifier_of(mem)) (\tokens(std::meta::parameter_list_of(mem))) = 0;
};
} else if (std::meta::is_variable(mem)) {
// Report a compile-time error (not yet a feature in C++)
}
}
return ret;
}
consteval void interface(info proto) noexcept {
string_view name = std::meta::identifier_of(proto);
std::meta::queue_injection(^^{
class \id(name) {
public:
// make interface functions
\tokens(makeInterfaceFunctions(proto))
// the destructor
virtual ~\id(name)() = default;
// the constructor
\id(name)() = default;
// delete the copy constructor
\id(name)(\id(name) const&) = delete;
// delete the copy assignment operator
void operator=(\id(name) const&) = delete;
};
});
}
// use "interface":
class(interface) IFoo {
int f();
void g(string s);
};
```
It would also be possible to apply multiple metaclass types. For example, for metaclasses `x` and `y`, one could write `class(x, y) MyClass { /* ... */ };`.
The paper proposes that this allows for abstractions to greatly decrease boilerplate by producing generated functions and customisable defaults, semantics, and constraints. It further abolishes the need to create new language feature proposals by allowing such features to be expressed using metaclass features.
## Support in languages and tools
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=6 "Edit section: Support in languages and tools")\]
The following are some of the most prominent [programming languages](https://en.wikipedia.org/wiki/Programming_language "Programming language") that support metaclasses.
- [Common Lisp](https://en.wikipedia.org/wiki/Common_Lisp "Common Lisp"), via [CLOS](https://en.wikipedia.org/wiki/Common_Lisp_Object_System "Common Lisp Object System")
- [Delphi](https://en.wikipedia.org/wiki/Delphi_\(programming_language\) "Delphi (programming language)") and other versions of [Object Pascal](https://en.wikipedia.org/wiki/Object_Pascal "Object Pascal") influenced by it
- [Groovy](https://en.wikipedia.org/wiki/Groovy_\(programming_language\) "Groovy (programming language)")
- [Objective-C](https://en.wikipedia.org/wiki/Objective-C "Objective-C")
- [ooRexx](https://en.wikipedia.org/wiki/Object_REXX "Object REXX")
- [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)")
- [Perl](https://en.wikipedia.org/wiki/Perl "Perl"), via the metaclass pragma, as well as [Moose](https://en.wikipedia.org/wiki/Moose_\(Perl\) "Moose (Perl)")
- [Ruby](https://en.wikipedia.org/wiki/Ruby_\(programming_language\) "Ruby (programming language)")
- [Smalltalk](https://en.wikipedia.org/wiki/Smalltalk "Smalltalk")
Some less widespread languages that support metaclasses include [OpenJava](https://en.wikipedia.org/wiki/OpenJava "OpenJava")[\[14\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-14), [OpenC++](https://en.wikipedia.org/wiki/OpenC%2B%2B "OpenC++")[\[15\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-15)[\[16\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-16), [OpenAda](https://en.wikipedia.org/w/index.php?title=OpenAda&action=edit&redlink=1 "OpenAda (page does not exist)"), [CorbaScript](https://en.wikipedia.org/wiki/CorbaScript "CorbaScript"), [ObjVLisp](https://en.wikipedia.org/w/index.php?title=ObjVLisp&action=edit&redlink=1 "ObjVLisp (page does not exist)"), [Object-Z](https://en.wikipedia.org/wiki/Object-Z "Object-Z"), [MODEL-K](https://en.wikipedia.org/w/index.php?title=MODEL-K&action=edit&redlink=1 "MODEL-K (page does not exist)"), [XOTcl](https://en.wikipedia.org/wiki/XOTcl "XOTcl"), and [MELDC](https://en.wikipedia.org/w/index.php?title=MELDC&action=edit&redlink=1 "MELDC (page does not exist)"). Several of these languages date from the early 1990s and are of academic interest.[\[17\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-17)
[Java](https://en.wikipedia.org/wiki/Java_\(programming_language\) "Java (programming language)") features `java.lang.Class<T>` for [introspection](https://en.wikipedia.org/wiki/Type_introspection "Type introspection"), similar to metaclasses, but are not actually metaclasses.
[Logtalk](https://en.wikipedia.org/wiki/Logtalk "Logtalk"), an object-oriented extension of [Prolog](https://en.wikipedia.org/wiki/Prolog "Prolog"), also supports metaclasses.
[Resource Description Framework](https://en.wikipedia.org/wiki/Resource_Description_Framework "Resource Description Framework") (RDF) and [Unified Modeling Language](https://en.wikipedia.org/wiki/Unified_Modeling_Language "Unified Modeling Language") (UML) both support metaclasses.
Metaclasses were a proposed for a possible inclusion in future version of [C++](https://en.wikipedia.org/wiki/C%2B%2B "C++"), but currently is not an included feature.[\[11\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses-11)
## See also
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=7 "Edit section: See also")\]
- [Metamodel](https://en.wikipedia.org/wiki/Metamodeling "Metamodeling")
- [Metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming "Metaprogramming")
- [Metaobject](https://en.wikipedia.org/wiki/Metaobject "Metaobject")
- [Kind (type theory)](https://en.wikipedia.org/wiki/Kind_\(type_theory\) "Kind (type theory)")
- [Reflection](https://en.wikipedia.org/wiki/Reflection_\(computer_science\) "Reflection (computer science)")
- [Dynamism](https://en.wikipedia.org/w/index.php?title=Dynamism_\(computing\)&action=edit&redlink=1 "Dynamism (computing) (page does not exist)")
- [Adapter pattern](https://en.wikipedia.org/wiki/Adapter_pattern "Adapter pattern")
- [Metaclass (Semantic Web)](https://en.wikipedia.org/wiki/Metaclass_\(Semantic_Web\) "Metaclass (Semantic Web)")
## References
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=8 "Edit section: References")\]
1. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-1)**
Forman, Ira R.; Danforth, Scott (1999). *Putting Metaclasses to Work*. Addison-Wesley. [ISBN](https://en.wikipedia.org/wiki/ISBN_\(identifier\) "ISBN (identifier)")
[0-201-43305-2](https://en.wikipedia.org/wiki/Special:BookSources/0-201-43305-2 "Special:BookSources/0-201-43305-2")
.
2. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-2)**
AloorRavi, Sulekha (2022). *Metaprogramming with Python*. Birmingham: Packt Publishing.
3. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-3)** IBM Metaclass programming in Python, parts [1](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) [Archived](https://web.archive.org/web/20080903123731/http://www.ibm.com/developerworks/linux/library/l-pymeta.html) 3 September 2008 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine"), [2](http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/) [Archived](https://web.archive.org/web/20080823041605/http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/) 23 August 2008 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine") and [3](http://www.ibm.com/developerworks/library/l-pymeta3.html) [Archived](https://web.archive.org/web/20090321060011/http://www.ibm.com/developerworks/library/l-pymeta3.html) 21 March 2009 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine")
4. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-4)** Artima Forum: Metaclasses in Python 3.0 [(part 1 of 2)](http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) [Archived](https://web.archive.org/web/20200924160227/http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) 24 September 2020 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine") [(part 2 of 2)](http://www.artima.com/forums/flat.jsp?forum=106&thread=236260) [Archived](https://web.archive.org/web/20160409052201/http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) 9 April 2016 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine")
5. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-5)**
Mertz, David. ["A Primer on Python Metaclass Programming"](https://web.archive.org/web/20030430162409/http://www.onlamp.com/lpt/a/3388). *[ONLamp](https://en.wikipedia.org/wiki/O%27Reilly_Media "O'Reilly Media")*. Archived from [the original](http://www.onlamp.com/lpt/a/3388) on 30 April 2003. Retrieved 28 June 2006.
6. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-6)**
["The Ruby Object Model: Comparison with Smalltalk-80"](http://www.atalon.cz/rb-om/ruby-object-model/co-smalltalk/). [Archived](https://web.archive.org/web/20200117034235/http://www.atalon.cz/rb-om/ruby-object-model/co-smalltalk/) from the original on 17 January 2020. Retrieved 10 February 2012.
7. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-7)**
Perrotta, Paolo (2010). [*Metaprogramming Ruby*](https://web.archive.org/web/20160609183320/https://pragprog.com/book/ppmetr/metaprogramming-ruby). Pragmatic Bookshelf. [ISBN](https://en.wikipedia.org/wiki/ISBN_\(identifier\) "ISBN (identifier)")
[978-1-934356-47-0](https://en.wikipedia.org/wiki/Special:BookSources/978-1-934356-47-0 "Special:BookSources/978-1-934356-47-0")
. Archived from [the original](http://pragprog.com/book/ppmetr/metaprogramming-ruby) on 9 June 2016. Retrieved 21 November 2013.
8. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-8)**
["Object Membership: The Core Structure of Object Technology"](http://www.atalon.cz/om/object-membership/). [Archived](https://web.archive.org/web/20210506232010/http://www.atalon.cz/om/object-membership/) from the original on 6 May 2021. Retrieved 24 August 2012.
9. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-9)**
["Struct"](https://docs.ruby-lang.org/en/master/Struct.html). [Archived](https://web.archive.org/web/20250503235609/https://docs.ruby-lang.org/en/master/Struct.html) from the original on 3 May 2025. Retrieved 28 April 2025.
10. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-10)**
["What is a meta-class in Objective-C?"](http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html). *Cocoa with Love*. 17 January 2010. [Archived](https://web.archive.org/web/20110806081915/http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html) from the original on 6 August 2011. Retrieved 22 July 2011.
11. ^ [***a***](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses_11-0) [***b***](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses_11-1)
[Sutter, Herb](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") (18 June 2017). ["P0707 R0 - Metaclasses"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0707r0.pdf) (PDF). *open-std.org*. WG21. [Archived](https://web.archive.org/web/20201111204111/http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0707r0.pdf) (PDF) from the original on 11 November 2020. Retrieved 8 August 2018.
12. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses2_12-0)**
[Sutter, Herb](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") (12 October 2024). ["Declarative class authoring using consteval functions + reflection + generation (aka: Metaclasses for generative C++)"](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p0707r5.pdf) (PDF). *open-std.org*. WG21. Retrieved 14 December 2025.
13. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-13)**
Andrei Alexandrescu, Barry Rezvin, Daveed Vandevoorde (16 July 2024). ["Code Injection with Token Sequences"](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3294r1.html). *open-std.org*. WG21.
`{{cite web}}`: CS1 maint: multiple names: authors list ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_multiple_names:_authors_list "Category:CS1 maint: multiple names: authors list"))
14. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-14)**
Michiaki Tatsubori (14 October 2007). ["OJ: An Extensible Java"](https://web.archive.org/web/20140813142000/http://www.csg.ci.i.u-tokyo.ac.jp/openjava/). *csg.ci.i.u-tokyo.ac.jp*. University of Tokyo. Archived from [the original](http://www.csg.ci.i.u-tokyo.ac.jp/openjava/) on 13 August 2014.
15. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-15)**
Shigeru Chiba (14 October 2007). ["OpenC++ Home Page"](https://web.archive.org/web/20140821053838/http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/openc++.html). *csg.ci.i.u-tokyo.ac.jp*. University of Tokyo. Archived from [the original](http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/openc++.html) on 21 August 2014.
16. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-16)**
Shigeru Chiba. ["Welcome to OpenC++"](https://opencxx.sourceforge.net/). *opencxx.sourceforge.net*. University of Tokyo. Retrieved 10 December 2025.
17. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-17)**
["An implementation of mixins in Java using metaclasses"](https://web.archive.org/web/20071016230949/http://csl.ensm-douai.fr/noury/uploads/1/nouryBouraqadi.Gpce03WorkshopOnRepls.pdf) (PDF). Archived from [the original](http://csl.ensm-douai.fr/noury/uploads/1/nouryBouraqadi.Gpce03WorkshopOnRepls.pdf) (PDF) on 16 October 2007. Retrieved 27 November 2007.
## External links
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=9 "Edit section: External links")\]
- [What Is a Metaclass?](http://www.atalon.cz/om/what-is-a-metaclass/)
| [v](https://en.wikipedia.org/wiki/Template:Data_types "Template:Data types") [t](https://en.wikipedia.org/wiki/Template_talk:Data_types "Template talk:Data types") [e](https://en.wikipedia.org/wiki/Special:EditPage/Template:Data_types "Special:EditPage/Template:Data types")[Data types](https://en.wikipedia.org/wiki/Data_type "Data type") | |
|---|---|
| [Uninterpreted](https://en.wikipedia.org/wiki/Units_of_information "Units of information") | [Bit](https://en.wikipedia.org/wiki/Bit "Bit") [Byte](https://en.wikipedia.org/wiki/Byte "Byte") [Trit](https://en.wikipedia.org/wiki/Ternary_numeral_system "Ternary numeral system") [Tryte](https://en.wikipedia.org/wiki/Ternary_numeral_system#Tryte "Ternary numeral system") [Word](https://en.wikipedia.org/wiki/Word_\(computer_architecture\) "Word (computer architecture)") [Bit array](https://en.wikipedia.org/wiki/Bit_array "Bit array") |
| Numeric | [Arbitrary-precision or bignum](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic "Arbitrary-precision arithmetic") [Complex](https://en.wikipedia.org/wiki/Complex_data_type "Complex data type") [Decimal](https://en.wikipedia.org/wiki/Decimal_data_type "Decimal data type") [Fixed point](https://en.wikipedia.org/wiki/Fixed-point_arithmetic "Fixed-point arithmetic") [Block floating point](https://en.wikipedia.org/wiki/Block_floating_point "Block floating point") [Floating point](https://en.wikipedia.org/wiki/Floating-point_arithmetic "Floating-point arithmetic") Reduced precision [Minifloat](https://en.wikipedia.org/wiki/Minifloat "Minifloat") [Half precision](https://en.wikipedia.org/wiki/Half-precision_floating-point_format "Half-precision floating-point format") [bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format "Bfloat16 floating-point format") [Single precision](https://en.wikipedia.org/wiki/Single-precision_floating-point_format "Single-precision floating-point format") [Double precision](https://en.wikipedia.org/wiki/Double-precision_floating-point_format "Double-precision floating-point format") [Quadruple precision](https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format "Quadruple-precision floating-point format") [Octuple precision](https://en.wikipedia.org/wiki/Octuple-precision_floating-point_format "Octuple-precision floating-point format") [Extended precision](https://en.wikipedia.org/wiki/Extended_precision "Extended precision") [Long double](https://en.wikipedia.org/wiki/Long_double "Long double") [Integer](https://en.wikipedia.org/wiki/Integer_\(computer_science\) "Integer (computer science)") [signedness](https://en.wikipedia.org/wiki/Signedness "Signedness") [Interval](https://en.wikipedia.org/wiki/Interval_arithmetic#Implementations "Interval arithmetic") [Rational](https://en.wikipedia.org/wiki/Rational_data_type "Rational data type") |
| [Reference](https://en.wikipedia.org/wiki/Reference_\(computer_science\) "Reference (computer science)") | [Address](https://en.wikipedia.org/wiki/Memory_address "Memory address") [physical](https://en.wikipedia.org/wiki/Physical_address "Physical address") [virtual](https://en.wikipedia.org/wiki/Virtual_address_space "Virtual address space") [Pointer](https://en.wikipedia.org/wiki/Pointer_\(computer_programming\) "Pointer (computer programming)") |
| [Text](https://en.wikipedia.org/wiki/Plain_text "Plain text") | [Character](https://en.wikipedia.org/wiki/Character_\(computing\) "Character (computing)") [String](https://en.wikipedia.org/wiki/String_\(computer_science\) "String (computer science)") [null-terminated](https://en.wikipedia.org/wiki/Null-terminated_string "Null-terminated string") |
| [Composite](https://en.wikipedia.org/wiki/Composite_data_type "Composite data type") | [Algebraic data type](https://en.wikipedia.org/wiki/Algebraic_data_type "Algebraic data type") [generalized](https://en.wikipedia.org/wiki/Generalized_algebraic_data_type "Generalized algebraic data type") [Array](https://en.wikipedia.org/wiki/Array_\(data_type\) "Array (data type)") [Associative array](https://en.wikipedia.org/wiki/Associative_array "Associative array") [Class](https://en.wikipedia.org/wiki/Class_\(programming\) "Class (programming)") [Dependent](https://en.wikipedia.org/wiki/Dependent_type "Dependent type") [Equality](https://en.wikipedia.org/wiki/Intuitionistic_type_theory#Equality_type "Intuitionistic type theory") [Inductive](https://en.wikipedia.org/wiki/Inductive_type "Inductive type") [Intersection](https://en.wikipedia.org/wiki/Intersection_type "Intersection type") [List](https://en.wikipedia.org/wiki/List_\(abstract_data_type\) "List (abstract data type)") [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\) "Object (computer science)") [metaobject](https://en.wikipedia.org/wiki/Metaobject "Metaobject") [Option type](https://en.wikipedia.org/wiki/Option_type "Option type") [Product](https://en.wikipedia.org/wiki/Product_type "Product type") [Record or Struct](https://en.wikipedia.org/wiki/Record_\(computer_science\) "Record (computer science)") [Refinement](https://en.wikipedia.org/wiki/Refinement_type "Refinement type") [Set](https://en.wikipedia.org/wiki/Set_\(abstract_data_type\) "Set (abstract data type)") [Union](https://en.wikipedia.org/wiki/Union_type "Union type") [tagged](https://en.wikipedia.org/wiki/Tagged_union "Tagged union") |
| Other | [Any type](https://en.wikipedia.org/wiki/Any_type "Any type") [Boolean](https://en.wikipedia.org/wiki/Boolean_data_type "Boolean data type") [Bottom type](https://en.wikipedia.org/wiki/Bottom_type "Bottom type") [Collection](https://en.wikipedia.org/wiki/Container_\(abstract_data_type\) "Container (abstract data type)") [Enumerated type](https://en.wikipedia.org/wiki/Enumerated_type "Enumerated type") [Exception](https://en.wikipedia.org/wiki/Exception_handling "Exception handling") [Function type](https://en.wikipedia.org/wiki/Function_type "Function type") [Opaque data type](https://en.wikipedia.org/wiki/Opaque_data_type "Opaque data type") [Recursive data type](https://en.wikipedia.org/wiki/Recursive_data_type "Recursive data type") [Semaphore](https://en.wikipedia.org/wiki/Semaphore_\(programming\) "Semaphore (programming)") [Stream](https://en.wikipedia.org/wiki/Stream_\(computing\) "Stream (computing)") [Strongly typed identifier](https://en.wikipedia.org/wiki/Strongly_typed_identifier "Strongly typed identifier") [Type class](https://en.wikipedia.org/wiki/Type_class "Type class") [Empty type](https://en.wikipedia.org/wiki/Empty_type "Empty type") [Unit type](https://en.wikipedia.org/wiki/Unit_type "Unit type") [Void](https://en.wikipedia.org/wiki/Void_type "Void type") |
| Related topics | [Value](https://en.wikipedia.org/wiki/Value_\(computer_science\) "Value (computer science)") [Abstract data type](https://en.wikipedia.org/wiki/Abstract_data_type "Abstract data type") [Boxing](https://en.wikipedia.org/wiki/Boxing_\(computer_programming\) "Boxing (computer programming)") [Data structure](https://en.wikipedia.org/wiki/Data_structure "Data structure") [Generic](https://en.wikipedia.org/wiki/Generic_programming "Generic programming") [Kind](https://en.wikipedia.org/wiki/Kind_\(type_theory\) "Kind (type theory)") [metaclass]() [Parametric polymorphism](https://en.wikipedia.org/wiki/Parametric_polymorphism "Parametric polymorphism") [Primitive data type](https://en.wikipedia.org/wiki/Primitive_data_type "Primitive data type") [Interface](https://en.wikipedia.org/wiki/Interface_\(object-oriented_programming\) "Interface (object-oriented programming)") [Subtyping](https://en.wikipedia.org/wiki/Subtyping "Subtyping") [Type constructor](https://en.wikipedia.org/wiki/Type_constructor "Type constructor") [Type conversion](https://en.wikipedia.org/wiki/Type_conversion "Type conversion") [Type system](https://en.wikipedia.org/wiki/Type_system "Type system") [Type theory](https://en.wikipedia.org/wiki/Type_theory "Type theory") [Variable](https://en.wikipedia.org/wiki/Variable_\(computer_science\) "Variable (computer science)") |
| [v](https://en.wikipedia.org/wiki/Template:Meta-prefix "Template:Meta-prefix") [t](https://en.wikipedia.org/wiki/Template_talk:Meta-prefix "Template talk:Meta-prefix") [e](https://en.wikipedia.org/wiki/Special:EditPage/Template:Meta-prefix "Special:EditPage/Template:Meta-prefix")[Meta-](https://en.wikipedia.org/wiki/Meta_\(prefix\) "Meta (prefix)") | |
|---|---|
| Domains and methods | [Meta-analysis](https://en.wikipedia.org/wiki/Meta-analysis "Meta-analysis") [Metabibliography](https://en.wikipedia.org/wiki/Metabibliography "Metabibliography") [Metaclass]() [Semantic Web](https://en.wikipedia.org/wiki/Metaclass_\(Semantic_Web\) "Metaclass (Semantic Web)") [Metacognition](https://en.wikipedia.org/wiki/Metacognition "Metacognition") [Meta-learning](https://en.wikipedia.org/wiki/Meta-learning "Meta-learning") [Metamemory](https://en.wikipedia.org/wiki/Metamemory "Metamemory") [Meta-communication](https://en.wikipedia.org/wiki/Meta-communication "Meta-communication") [Metacomputing](https://en.wikipedia.org/wiki/Metacomputing "Metacomputing") [Metadata](https://en.wikipedia.org/wiki/Metadata "Metadata") [Metadesign](https://en.wikipedia.org/wiki/Metadesign "Metadesign") [Metadiscourse](https://en.wikipedia.org/wiki/Metadiscourse "Metadiscourse") [Meta-emotion](https://en.wikipedia.org/wiki/Meta-emotion "Meta-emotion") [Metamood](https://en.wikipedia.org/wiki/Metamood "Metamood") [Metafiction](https://en.wikipedia.org/wiki/Metafiction "Metafiction") [Metagaming](https://en.wikipedia.org/wiki/Metagaming "Metagaming") [Metagenomics](https://en.wikipedia.org/wiki/Metagenomics "Metagenomics") [Metaheuristic](https://en.wikipedia.org/wiki/Metaheuristic "Metaheuristic") [Metahumor](https://en.wikipedia.org/wiki/Self-referential_humor "Self-referential humor") [Metaknowledge](https://en.wikipedia.org/wiki/Metaknowledge "Metaknowledge") [Metalanguage](https://en.wikipedia.org/wiki/Metalanguage "Metalanguage") [Metapragmatics](https://en.wikipedia.org/wiki/Metapragmatics "Metapragmatics") [Metasemantics](https://en.wikipedia.org/wiki/Metasemantics "Metasemantics") [Metasyntax](https://en.wikipedia.org/wiki/Metasyntax "Metasyntax") [Metalinguistics](https://en.wikipedia.org/wiki/Metalinguistics "Metalinguistics") [Metamaterials](https://en.wikipedia.org/wiki/Metamaterials "Metamaterials") [Metamedia](https://en.wikipedia.org/wiki/Metamedia "Metamedia") [Metamodeling](https://en.wikipedia.org/wiki/Metamodeling "Metamodeling") [Metamodernism](https://en.wikipedia.org/wiki/Metamodernism "Metamodernism") [Metamotivation](https://en.wikipedia.org/wiki/Metamotivation "Metamotivation") [Metanarrative](https://en.wikipedia.org/wiki/Metanarrative "Metanarrative") [Metaobject](https://en.wikipedia.org/wiki/Metaobject "Metaobject") [Meta-optimization](https://en.wikipedia.org/wiki/Meta-optimization "Meta-optimization") [Meta-organization](https://en.wikipedia.org/wiki/Meta-organization "Meta-organization") [Metaphenomics](https://en.wikipedia.org/wiki/Metaphenomics "Metaphenomics") [Metapolitics](https://en.wikipedia.org/wiki/Metapolitics "Metapolitics") [Metapopulation](https://en.wikipedia.org/wiki/Metapopulation "Metapopulation") [Metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming "Metaprogramming") [Metapsychiatry](https://en.wikipedia.org/wiki/Metapsychiatry "Metapsychiatry") [Metapsychology](https://en.wikipedia.org/wiki/Metapsychology "Metapsychology") [Metapuzzle](https://en.wikipedia.org/wiki/Metapuzzle "Metapuzzle") [Meta-reference](https://en.wikipedia.org/wiki/Meta-reference "Meta-reference") [Meta-regulation](https://en.wikipedia.org/wiki/Meta-regulation "Meta-regulation") [Meta-system](https://en.wikipedia.org/wiki/Meta-system "Meta-system") [Metatheorem](https://en.wikipedia.org/wiki/Metatheorem "Metatheorem") [Metatheory](https://en.wikipedia.org/wiki/Metatheory "Metatheory") [Metaverse](https://en.wikipedia.org/wiki/Metaverse "Metaverse") [Metascience](https://en.wikipedia.org/wiki/Metascience "Metascience") domains [Metahistory](https://en.wikipedia.org/wiki/Metahistory_\(concept\) "Metahistory (concept)") [Metamathematics](https://en.wikipedia.org/wiki/Metamathematics "Metamathematics") [Metasociology](https://en.wikipedia.org/wiki/Sociology_of_sociology "Sociology of sociology") [Philosophy](https://en.wikipedia.org/wiki/Philosophy "Philosophy") domains [Metaepistemology](https://en.wikipedia.org/wiki/Metaepistemology "Metaepistemology") [Metaethics](https://en.wikipedia.org/wiki/Metaethics "Metaethics") [Metalogic](https://en.wikipedia.org/wiki/Metalogic "Metalogic") [Metaphilosophy](https://en.wikipedia.org/wiki/Metaphilosophy "Metaphilosophy") [Metaphysics](https://en.wikipedia.org/wiki/Metaphysics "Metaphysics") [Metametaphysics](https://en.wikipedia.org/wiki/Metametaphysics "Metametaphysics") [Meta-ontology](https://en.wikipedia.org/wiki/Meta-ontology "Meta-ontology") [Metasemantics](https://en.wikipedia.org/wiki/Metasemantics "Metasemantics") |

Retrieved from "<https://en.wikipedia.org/w/index.php?title=Metaclass&oldid=1327572642>"
[Category](https://en.wikipedia.org/wiki/Help:Category "Help:Category"):
- [Class (computer programming)](https://en.wikipedia.org/wiki/Category:Class_\(computer_programming\) "Category:Class (computer programming)")
Hidden categories:
- [Webarchive template wayback links](https://en.wikipedia.org/wiki/Category:Webarchive_template_wayback_links "Category:Webarchive template wayback links")
- [CS1 maint: multiple names: authors list](https://en.wikipedia.org/wiki/Category:CS1_maint:_multiple_names:_authors_list "Category:CS1 maint: multiple names: authors list")
- [Articles with short description](https://en.wikipedia.org/wiki/Category:Articles_with_short_description "Category:Articles with short description")
- [Short description is different from Wikidata](https://en.wikipedia.org/wiki/Category:Short_description_is_different_from_Wikidata "Category:Short description is different from Wikidata")
- [Articles that may contain original research from September 2013](https://en.wikipedia.org/wiki/Category:Articles_that_may_contain_original_research_from_September_2013 "Category:Articles that may contain original research from September 2013")
- [All articles that may contain original research](https://en.wikipedia.org/wiki/Category:All_articles_that_may_contain_original_research "Category:All articles that may contain original research")
- [Articles needing additional references from September 2013](https://en.wikipedia.org/wiki/Category:Articles_needing_additional_references_from_September_2013 "Category:Articles needing additional references from September 2013")
- [All articles needing additional references](https://en.wikipedia.org/wiki/Category:All_articles_needing_additional_references "Category:All articles needing additional references")
- [Articles with multiple maintenance issues](https://en.wikipedia.org/wiki/Category:Articles_with_multiple_maintenance_issues "Category:Articles with multiple maintenance issues")
- [Use dmy dates from October 2025](https://en.wikipedia.org/wiki/Category:Use_dmy_dates_from_October_2025 "Category:Use dmy dates from October 2025")
- [Articles needing additional references from October 2013](https://en.wikipedia.org/wiki/Category:Articles_needing_additional_references_from_October_2013 "Category:Articles needing additional references from October 2013")
- [All accuracy disputes](https://en.wikipedia.org/wiki/Category:All_accuracy_disputes "Category:All accuracy disputes")
- [Articles with disputed statements from May 2015](https://en.wikipedia.org/wiki/Category:Articles_with_disputed_statements_from_May_2015 "Category:Articles with disputed statements from May 2015")
- [Wikipedia articles with style issues from September 2013](https://en.wikipedia.org/wiki/Category:Wikipedia_articles_with_style_issues_from_September_2013 "Category:Wikipedia articles with style issues from September 2013")
- [All articles with style issues](https://en.wikipedia.org/wiki/Category:All_articles_with_style_issues "Category:All articles with style issues")
- [Articles with example Python (programming language) code](https://en.wikipedia.org/wiki/Category:Articles_with_example_Python_\(programming_language\)_code "Category:Articles with example Python (programming language) code")
- This page was last edited on 15 December 2025, at 01:34 (UTC).
- Text is available under the [Creative Commons Attribution-ShareAlike 4.0 License](https://en.wikipedia.org/wiki/Wikipedia:Text_of_the_Creative_Commons_Attribution-ShareAlike_4.0_International_License "Wikipedia:Text of the Creative Commons Attribution-ShareAlike 4.0 International License"); additional terms may apply. By using this site, you agree to the [Terms of Use](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Terms_of_Use "foundation:Special:MyLanguage/Policy:Terms of Use") and [Privacy Policy](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy "foundation:Special:MyLanguage/Policy:Privacy policy"). Wikipedia® is a registered trademark of the [Wikimedia Foundation, Inc.](https://wikimediafoundation.org/), a non-profit organization.
- [Privacy policy](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy)
- [About Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:About)
- [Disclaimers](https://en.wikipedia.org/wiki/Wikipedia:General_disclaimer)
- [Contact Wikipedia](https://en.wikipedia.org/wiki/Wikipedia:Contact_us)
- [Legal & safety contacts](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Legal:Wikimedia_Foundation_Legal_and_Safety_Contact_Information)
- [Code of Conduct](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Universal_Code_of_Conduct)
- [Developers](https://developer.wikimedia.org/)
- [Statistics](https://stats.wikimedia.org/#/en.wikipedia.org)
- [Cookie statement](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Cookie_statement)
- [Mobile view](https://en.wikipedia.org/w/index.php?title=Metaclass&mobileaction=toggle_view_mobile)
- [](https://www.wikimedia.org/)
- [](https://www.mediawiki.org/)
Search
Toggle the table of contents
Metaclass
12 languages
[Add topic](https://en.wikipedia.org/wiki/Metaclass) |
| Readable Markdown | In [object-oriented programming](https://en.wikipedia.org/wiki/Object-oriented_programming "Object-oriented programming"), a **metaclass** is a [class](https://en.wikipedia.org/wiki/Class_\(computer_science\) "Class (computer science)") whose [syntactic](https://en.wikipedia.org/wiki/Syntax_\(programming_language\) "Syntax (programming language)") definitions are used for the syntactic definition of the classes themselves. Unlike ordinary classes, which define the behaviors of objects, metaclasses specify the behaviors of classes and their instances. Not all object-oriented [programming languages](https://en.wikipedia.org/wiki/Programming_languages "Programming languages") support the concept of metaclasses. For those that do, the extent of control metaclasses have over class behaviors varies. Metaclasses are often implemented by treating classes as [first-class citizens](https://en.wikipedia.org/wiki/First-class_citizen "First-class citizen"), making a metaclass an object that creates and manages these classes. Each programming language adheres to its own [metaobject protocol](https://en.wikipedia.org/wiki/Metaobject_protocol "Metaobject protocol"), which are the rules that determine interactions among objects, classes, and metaclasses.[\[1\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-1) Metaclasses are utilized to automate code generation and to enhance framework development.[\[2\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-2)
In [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)"), the builtin class `type` is a metaclass.[\[3\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-3)[\[4\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-4)[\[5\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-5) Consider this simple Python class:
```
class Car:
make: str
model: str
year: int
color: str
def __init__(self, make: str, model: str, year: int, color: str) -> None:
self.make = make
self.model = model
self.year = year
self.color = color
@property
def description(self) -> str:
"""
Return a description of this car.
"""
return f"{self.color} {self.make} {self.model}"
```
At run time, `Car` itself is an instance of `type`. The source code of the `Car` class, shown above, does not include such details as the size in bytes of `Car` objects, their binary layout in memory, how they are allocated, that the `__init__` method is automatically called each time a `Car` is created, and so on. These details come into play not only when a new `Car` object is created, but also each time any attribute of a `Car` is accessed. In languages without metaclasses, these details are defined by the language specification and can't be overridden. In Python, the metaclass - `type` - controls these details of `Car`'s behavior. They can be overridden by using a different metaclass instead of `type`.
The above example contains some redundant code to do with the four attributes `make`, `model`, `year`, and `color`. It is possible to eliminate some of this redundancy using a custom metaclass. In Python, a metaclass is most easily defined as a subclass of `type`.
```
from typing import Any
class AttributeInitType(type):
def __call__(self, *args: tuple[Any], **kwargs: dict[str, Any]) -> object:
"""
Create a new instance.
"""
# First, create the object in the normal default way.
obj: object = type.__call__(self, *args)
# Additionally, set attributes on the new object.
for name, value in kwargs.items():
setattr(obj, name, value)
# Return the new object.
return obj
```
This metaclass only overrides object creation. All other aspects of class and object behavior are still handled by `type`.
Now the class `Car` can be rewritten to use this metaclass. In Python 3 this is done by providing a "keyword argument" `metaclass` to the class definition:
```
class Car(object, metaclass=AttributeInitType):
@property
def description(self) -> str:
"""
Return a description of this car.
"""
return " ".join(str(value) for value in self.__dict__.values())
```
The resulting object `Car` can be instantiated as usual, but can contain any number of keyword arguments:
```
new_car: Car = Car(make='Toyota', model='Prius', year=2005, color='Green', engine='Hybrid')
```
[](https://en.wikipedia.org/wiki/File:Smalltalk_80_metaclasses.svg)
The Smalltalk-80 metaclass hierarchy as a UML diagram
[](https://en.wikipedia.org/wiki/File:Smalltalk_metaclass.png)
Diagram of the inheritance and instance relationships between classes and metaclasses in Smalltalk
In [Smalltalk](https://en.wikipedia.org/wiki/Smalltalk "Smalltalk"), everything is an [object](https://en.wikipedia.org/wiki/Object_\(computer_science\) "Object (computer science)"). Additionally, Smalltalk is a [class based](https://en.wikipedia.org/wiki/Class-based_programming "Class-based programming") system, which means that every object has a class that defines the structure of that object (i.e. the instance variables the object has) and the messages an object understands. Together this implies that a class in Smalltalk is an object and that, therefore a class needs to be an instance of a class (called metaclass).
As an example, a car object `c` is an instance of the class `Car`. In turn, the class `Car` is again an object and as such an instance of the metaclass of `Car` called `Car class`. Note the blank in the name of the metaclass. The name of the metaclass is the Smalltalk expression that, when evaluated, results in the metaclass object. Thus evaluating `Car class` results in the metaclass object for `Car` whose name is `Car class` (one can confirm this by evaluating `Car class name` which returns the name of the metaclass of `Car`.)
[Class methods](https://en.wikipedia.org/wiki/Class_method "Class method") actually belong to the metaclass, just as instance methods actually belong to the class. When a message is sent to the object `2`, the search for the method starts in `Integer`. If it is not found it proceeds up the superclass chain, stopping at Object whether it is found or not.
When a message is sent to `Integer` the search for the method starts in `Integer class` and proceeds up the superclass chain to `Object class`. Note that, so far, the metaclass inheritance chain exactly follows that of the class inheritance chain. But the metaclass chain extends further because `Object class` is the subclass of `Class`. All metaclasses are subclasses of Class.
In early Smalltalks, there was only one metaclass called `Class`. This implied that the [methods](https://en.wikipedia.org/wiki/Method_\(computer_science\) "Method (computer science)") all classes have were the same, in particular the method to create new objects, i.e., `new`. To allow classes to have their own methods and their own instance variables (called class instance variables and should not be confused with [class variables](https://en.wikipedia.org/wiki/Class_variable "Class variable")), Smalltalk-80 introduced for each class `C` their own metaclass `C class`. This means that each metaclass is effectively a [singleton](https://en.wikipedia.org/wiki/Singleton_pattern "Singleton pattern") class.
Since there is no requirement that metaclasses behave differently from each other, all metaclasses are instances of only one class called `Metaclass`. The metaclass of `Metaclass` is called `Metaclass class` which again is an instance of class `Metaclass`.
In Smalltalk-80, every class (except `Object`) has a [superclass](https://en.wikipedia.org/wiki/Superclass_\(computer_science\) "Superclass (computer science)"). The [abstract superclass](https://en.wikipedia.org/wiki/Abstract_superclass "Abstract superclass") of all metaclasses is `Class`, which describes the general nature of classes.
The superclass hierarchy for metaclasses parallels that for classes, except for class `Object`. ALL metaclasses are subclasses of `Class`, therefore:
- `Object class superclass == Class.`
Like [conjoined twins](https://en.wikipedia.org/wiki/Conjoined_twins "Conjoined twins"), classes and metaclasses are born together. `Metaclass` has an instance variable `thisClass`, which points to its conjoined class. Note that the usual Smalltalk [class browser](https://en.wikipedia.org/wiki/Class_browser "Class browser") does not show metaclasses as separate classes. Instead the class browser allows to edit the class together with its metaclass at the same time.
The names of classes in the metaclass hierarchy are easily confused with the concepts of the same name. For instance:
- `Object` is the base class that provides common methods for all objects; "an object" is an integer, or a widget, or a `Car`, etc.
- `Class` is the base of the metaclasses that provides common methods for all classes (though it is not a metaclass itself); "a class" is something like `Integer`, or `Widget`, or `Car`, etc.
- `Metaclass` provides common methods for all metaclasses.
Four classes provide the facilities to describe new classes. Their [inheritance hierarchy](https://en.wikipedia.org/wiki/Inheritance_hierarchy "Inheritance hierarchy") (from Object), and the main facilities they provide are:
Object - default behavior common to all objects, like class access
Behavior - minimum [state](https://en.wikipedia.org/wiki/State_\(computer_science\) "State (computer science)") for [compiling](https://en.wikipedia.org/wiki/Compiling "Compiling") methods and creating/running objects
ClassDescription ([abstract class](https://en.wikipedia.org/wiki/Abstract_class "Abstract class")) - class/variable naming, comments
Class - similar, more comprehensive, facilities to superclasses
Metaclass - initializing class variables, instance creation messages
Ruby purifies the Smalltalk-80 concept of metaclasses by introducing [eigenclasses](https://en.wiktionary.org/wiki/eigenclasses "wiktionary:eigenclasses"), removing the `Metaclass` class, and (un)redefining the class-of map. The change can be schematized as follows:[\[6\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-6)
| | | |
|---|---|---|
| | → | |
| | | |
| Classes | **Implicit metaclasses** | |
| Terminal objects | | |
| | | |
| Classes | **Eigenclasses of classes** | **Eigenclasses of eigenclasses** |
| Terminal objects | **Eigenclasses of terminal objects** | |
Note in particular the correspondence between Smalltalk's implicit metaclasses and Ruby's eigenclasses of classes. The Ruby eigenclass model makes the concept of implicit metaclasses fully uniform: every object *x* has its own meta-object, called the *eigenclass* of *x*, which is one meta-level higher than *x*. The "higher order" eigenclasses usually exist purely conceptually – they do not contain any methods or store any (other) data in most Ruby programs.[\[7\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-7)
The following diagrams show a sample core structure of Smalltalk-80 and Ruby in comparison.[\[8\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-8) In both languages, the structure consists of a built-in part which contains the circular objects (i.e. objects that appear in a cycle formed by a combination of blue or green links) and a user-part which has four explicit objects: classes `A` and `B` and terminal objects `u` and `v`. Green links show the child→parent relation of inheritance (with the implicit upward direction), blue links show the complementary member→container relation of instantiation (a blue link from *x* points to the least actual container of *x* that is the start point for the method lookup when a method is invoked on *x*). Gray nodes display the eigenclasses (resp. implicit metaclasses in the case of Smalltalk-80).
The diagram on the right also provides a picture of [lazy evaluation](https://en.wikipedia.org/wiki/Lazy_evaluation "Lazy evaluation") of eigenclasses in Ruby. The `v` object can have its eigenclass evaluated (allocated) as a consequence of adding *singleton methods* to `v`.
According to the Ruby's introspection method named `class`, the class of every class (and of every eigenclass) is constantly the `Class` class (denoted by `c` in the diagram). `Class`, and `Struct` are the only classes that have classes as instances.[\[9\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-9) \[*[disputed](https://en.wikipedia.org/wiki/Wikipedia:Disputed_statement "Wikipedia:Disputed statement") – [discuss](https://en.wikipedia.org/wiki/Talk:Metaclass#The_Struct_class_in_Ruby "Talk:Metaclass")*\] Subclassing of `Class` is disallowed. Following the standard definition of metaclasses we can conclude that `Class` and `Struct` are the only metaclasses in Ruby. This seems to contradict the correspondence between Ruby and Smalltalk, since in Smalltalk-80, every class has its own metaclass. The discrepancy is based on the disagreement between the `class` introspection method in Ruby and Smalltalk. While the map *x ↦ x.*`class` coincides on terminal objects, it differs in the restriction to classes. As already mentioned above, for a class `x`, the Ruby expression `x.class` evaluates constantly to `Class`. In Smalltalk-80, if `x` is a class then the expression `x class` corresponds to the Ruby's `x.singleton_class` – which evaluates to the eigenclass of `x`.
[](https://en.wikipedia.org/wiki/File:Objective-C_metaclass.png)
Diagram of the inheritance and instance relationships between classes and metaclasses in Objective-C. Note that Objective-C has multiple root classes; each root class would have a separate hierarchy. This diagram only shows the hierarchy for an example root class NSObject. Each other root class would have a similar hierarchy.
Metaclasses in Objective-C are almost the same as those in Smalltalk-80—not surprising since Objective-C borrows a lot from Smalltalk. Like Smalltalk, in Objective-C, the instance variables and methods are defined by an object's class. A class is an object, hence it is an instance of a metaclass.
Like Smalltalk, in Objective-C, class methods are simply methods called on the class object, hence a class's class methods must be defined as instance methods in its metaclass. Because different classes can have different sets of class methods, each class must have its own separate metaclass. Classes and metaclasses are always created as a pair: the runtime has functions `objc_allocateClassPair()` and `objc_registerClassPair()` to create and register class-metaclass pairs, respectively.
There are no names for the metaclasses; however, a pointer to any class object can be referred to with the generic type `Class` (similar to the type `id` being used for a pointer to any object).
Because class methods are inherited through inheritance, like Smalltalk, metaclasses must follow an inheritance scheme paralleling that of classes (e.g. if class A's parent class is class B, then A's metaclass's parent class is B's metaclass), except that of the root class.
Unlike Smalltalk, the metaclass of the root class inherits from the root class (usually `NSObject` using the [Cocoa](https://en.wikipedia.org/wiki/Cocoa_\(API\) "Cocoa (API)") framework) itself. This ensures that all class objects are ultimately instances of the root class, so that you can use the instance methods of the root class, usually useful utility methods for objects, on class objects themselves.
Since metaclass objects do not behave differently (you cannot add class methods for a metaclass, so metaclass objects all have the same methods), they are all instances of the same class—the metaclass of the root class (unlike Smalltalk). Thus, the metaclass of the root class is an instance of itself. The reason for this is that all metaclasses inherit from root class; hence, they must inherit the class methods of the root class.[\[10\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-10)
[Herb Sutter](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") of the ISO C++ Committee, first proposed the inclusion of metaclasses to C++ for [C++20](https://en.wikipedia.org/wiki/C%2B%2B20 "C++20") using [C++17](https://en.wikipedia.org/wiki/C%2B%2B17 "C++17") features.[\[11\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses-11) With the adoption of [reflection](https://en.wikipedia.org/wiki/Reflective_programming "Reflective programming") in [C++26](https://en.wikipedia.org/wiki/C%2B%2B26 "C++26"), this paper was revised.[\[12\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses2-12)
Its primary goal is to expand C++ abstraction beyond defined vocabulary (`class`, `struct`, `union`, `enum`, etc.) to allow adoptable vocabulary (such as `interface`, `value`), for the purpose of a more liberal approach to programming free of rule-memorisation. This feature would also allow non-standard features (such as [interfaces](https://en.wikipedia.org/wiki/Interface_\(object-oriented_programming\) "Interface (object-oriented programming)")) to be expressed as core features within libraries, and eliminate the necessity of specialised compilers (such as [Qt moc](https://en.wikipedia.org/wiki/Qt_\(software\)#Metaobject_compiler "Qt (software)"), [C++/CX](https://en.wikipedia.org/wiki/C%2B%2B/CX "C++/CX"), etc.) to express specific information using standardised features.
Using [code injection](https://en.wikipedia.org/wiki/Automatic_programming "Automatic programming") (another proposed addition to C++ reflection which would add token sequence injection into source code)[\[13\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-13), one would be able to create a Java/C\# style "`interface`" using a `consteval` function:
```
import std;
using std::string;
using std::string_view;
using std::meta::info;
[[nodiscard]]
consteval info makeInterfaceFunctions(info proto) noexcept {
info ret = ^^{};
for (info mem: std::meta::members_of(proto)) {
if (std::meta::is_nonspecial_member_function(mem)) {
ret = ^^{
\tokens(ret)
virtual [:\(std::meta::return_type_of(mem)):]
\id(std::meta::identifier_of(mem)) (\tokens(std::meta::parameter_list_of(mem))) = 0;
};
} else if (std::meta::is_variable(mem)) {
// Report a compile-time error (not yet a feature in C++)
}
}
return ret;
}
consteval void interface(info proto) noexcept {
string_view name = std::meta::identifier_of(proto);
std::meta::queue_injection(^^{
class \id(name) {
public:
// make interface functions
\tokens(makeInterfaceFunctions(proto))
// the destructor
virtual ~\id(name)() = default;
// the constructor
\id(name)() = default;
// delete the copy constructor
\id(name)(\id(name) const&) = delete;
// delete the copy assignment operator
void operator=(\id(name) const&) = delete;
};
});
}
// use "interface":
class(interface) IFoo {
int f();
void g(string s);
};
```
It would also be possible to apply multiple metaclass types. For example, for metaclasses `x` and `y`, one could write `class(x, y) MyClass { /* ... */ };`.
The paper proposes that this allows for abstractions to greatly decrease boilerplate by producing generated functions and customisable defaults, semantics, and constraints. It further abolishes the need to create new language feature proposals by allowing such features to be expressed using metaclass features.
## Support in languages and tools
\[[edit](https://en.wikipedia.org/w/index.php?title=Metaclass&action=edit§ion=6 "Edit section: Support in languages and tools")\]
The following are some of the most prominent [programming languages](https://en.wikipedia.org/wiki/Programming_language "Programming language") that support metaclasses.
- [Common Lisp](https://en.wikipedia.org/wiki/Common_Lisp "Common Lisp"), via [CLOS](https://en.wikipedia.org/wiki/Common_Lisp_Object_System "Common Lisp Object System")
- [Delphi](https://en.wikipedia.org/wiki/Delphi_\(programming_language\) "Delphi (programming language)") and other versions of [Object Pascal](https://en.wikipedia.org/wiki/Object_Pascal "Object Pascal") influenced by it
- [Groovy](https://en.wikipedia.org/wiki/Groovy_\(programming_language\) "Groovy (programming language)")
- [Objective-C](https://en.wikipedia.org/wiki/Objective-C "Objective-C")
- [ooRexx](https://en.wikipedia.org/wiki/Object_REXX "Object REXX")
- [Python](https://en.wikipedia.org/wiki/Python_\(programming_language\) "Python (programming language)")
- [Perl](https://en.wikipedia.org/wiki/Perl "Perl"), via the metaclass pragma, as well as [Moose](https://en.wikipedia.org/wiki/Moose_\(Perl\) "Moose (Perl)")
- [Ruby](https://en.wikipedia.org/wiki/Ruby_\(programming_language\) "Ruby (programming language)")
- [Smalltalk](https://en.wikipedia.org/wiki/Smalltalk "Smalltalk")
Some less widespread languages that support metaclasses include [OpenJava](https://en.wikipedia.org/wiki/OpenJava "OpenJava")[\[14\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-14), [OpenC++](https://en.wikipedia.org/wiki/OpenC%2B%2B "OpenC++")[\[15\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-15)[\[16\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-16), [OpenAda](https://en.wikipedia.org/w/index.php?title=OpenAda&action=edit&redlink=1 "OpenAda (page does not exist)"), [CorbaScript](https://en.wikipedia.org/wiki/CorbaScript "CorbaScript"), [ObjVLisp](https://en.wikipedia.org/w/index.php?title=ObjVLisp&action=edit&redlink=1 "ObjVLisp (page does not exist)"), [Object-Z](https://en.wikipedia.org/wiki/Object-Z "Object-Z"), [MODEL-K](https://en.wikipedia.org/w/index.php?title=MODEL-K&action=edit&redlink=1 "MODEL-K (page does not exist)"), [XOTcl](https://en.wikipedia.org/wiki/XOTcl "XOTcl"), and [MELDC](https://en.wikipedia.org/w/index.php?title=MELDC&action=edit&redlink=1 "MELDC (page does not exist)"). Several of these languages date from the early 1990s and are of academic interest.[\[17\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-17)
[Java](https://en.wikipedia.org/wiki/Java_\(programming_language\) "Java (programming language)") features `java.lang.Class<T>` for [introspection](https://en.wikipedia.org/wiki/Type_introspection "Type introspection"), similar to metaclasses, but are not actually metaclasses.
[Logtalk](https://en.wikipedia.org/wiki/Logtalk "Logtalk"), an object-oriented extension of [Prolog](https://en.wikipedia.org/wiki/Prolog "Prolog"), also supports metaclasses.
[Resource Description Framework](https://en.wikipedia.org/wiki/Resource_Description_Framework "Resource Description Framework") (RDF) and [Unified Modeling Language](https://en.wikipedia.org/wiki/Unified_Modeling_Language "Unified Modeling Language") (UML) both support metaclasses.
Metaclasses were a proposed for a possible inclusion in future version of [C++](https://en.wikipedia.org/wiki/C%2B%2B "C++"), but currently is not an included feature.[\[11\]](https://en.wikipedia.org/wiki/Metaclass#cite_note-SutterMetaclasses-11)
- [Metamodel](https://en.wikipedia.org/wiki/Metamodeling "Metamodeling")
- [Metaprogramming](https://en.wikipedia.org/wiki/Metaprogramming "Metaprogramming")
- [Metaobject](https://en.wikipedia.org/wiki/Metaobject "Metaobject")
- [Kind (type theory)](https://en.wikipedia.org/wiki/Kind_\(type_theory\) "Kind (type theory)")
- [Reflection](https://en.wikipedia.org/wiki/Reflection_\(computer_science\) "Reflection (computer science)")
- [Dynamism](https://en.wikipedia.org/w/index.php?title=Dynamism_\(computing\)&action=edit&redlink=1 "Dynamism (computing) (page does not exist)")
- [Adapter pattern](https://en.wikipedia.org/wiki/Adapter_pattern "Adapter pattern")
- [Metaclass (Semantic Web)](https://en.wikipedia.org/wiki/Metaclass_\(Semantic_Web\) "Metaclass (Semantic Web)")
1. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-1)**
Forman, Ira R.; Danforth, Scott (1999). *Putting Metaclasses to Work*. Addison-Wesley. [ISBN](https://en.wikipedia.org/wiki/ISBN_\(identifier\) "ISBN (identifier)")
[0-201-43305-2](https://en.wikipedia.org/wiki/Special:BookSources/0-201-43305-2 "Special:BookSources/0-201-43305-2")
.
2. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-2)**
AloorRavi, Sulekha (2022). *Metaprogramming with Python*. Birmingham: Packt Publishing.
3. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-3)** IBM Metaclass programming in Python, parts [1](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) [Archived](https://web.archive.org/web/20080903123731/http://www.ibm.com/developerworks/linux/library/l-pymeta.html) 3 September 2008 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine"), [2](http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/) [Archived](https://web.archive.org/web/20080823041605/http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/) 23 August 2008 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine") and [3](http://www.ibm.com/developerworks/library/l-pymeta3.html) [Archived](https://web.archive.org/web/20090321060011/http://www.ibm.com/developerworks/library/l-pymeta3.html) 21 March 2009 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine")
4. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-4)** Artima Forum: Metaclasses in Python 3.0 [(part 1 of 2)](http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) [Archived](https://web.archive.org/web/20200924160227/http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) 24 September 2020 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine") [(part 2 of 2)](http://www.artima.com/forums/flat.jsp?forum=106&thread=236260) [Archived](https://web.archive.org/web/20160409052201/http://www.artima.com/forums/flat.jsp?forum=106&thread=236234) 9 April 2016 at the [Wayback Machine](https://en.wikipedia.org/wiki/Wayback_Machine "Wayback Machine")
5. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-5)**
Mertz, David. ["A Primer on Python Metaclass Programming"](https://web.archive.org/web/20030430162409/http://www.onlamp.com/lpt/a/3388). *[ONLamp](https://en.wikipedia.org/wiki/O%27Reilly_Media "O'Reilly Media")*. Archived from [the original](http://www.onlamp.com/lpt/a/3388) on 30 April 2003. Retrieved 28 June 2006.
6. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-6)**
["The Ruby Object Model: Comparison with Smalltalk-80"](http://www.atalon.cz/rb-om/ruby-object-model/co-smalltalk/). [Archived](https://web.archive.org/web/20200117034235/http://www.atalon.cz/rb-om/ruby-object-model/co-smalltalk/) from the original on 17 January 2020. Retrieved 10 February 2012.
7. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-7)**
Perrotta, Paolo (2010). [*Metaprogramming Ruby*](https://web.archive.org/web/20160609183320/https://pragprog.com/book/ppmetr/metaprogramming-ruby). Pragmatic Bookshelf. [ISBN](https://en.wikipedia.org/wiki/ISBN_\(identifier\) "ISBN (identifier)")
[978-1-934356-47-0](https://en.wikipedia.org/wiki/Special:BookSources/978-1-934356-47-0 "Special:BookSources/978-1-934356-47-0")
. Archived from [the original](http://pragprog.com/book/ppmetr/metaprogramming-ruby) on 9 June 2016. Retrieved 21 November 2013.
8. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-8)**
["Object Membership: The Core Structure of Object Technology"](http://www.atalon.cz/om/object-membership/). [Archived](https://web.archive.org/web/20210506232010/http://www.atalon.cz/om/object-membership/) from the original on 6 May 2021. Retrieved 24 August 2012.
9. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-9)**
["Struct"](https://docs.ruby-lang.org/en/master/Struct.html). [Archived](https://web.archive.org/web/20250503235609/https://docs.ruby-lang.org/en/master/Struct.html) from the original on 3 May 2025. Retrieved 28 April 2025.
10. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-10)**
["What is a meta-class in Objective-C?"](http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html). *Cocoa with Love*. 17 January 2010. [Archived](https://web.archive.org/web/20110806081915/http://cocoawithlove.com/2010/01/what-is-meta-class-in-objective-c.html) from the original on 6 August 2011. Retrieved 22 July 2011.
11. ^ [***a***](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses_11-0) [***b***](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses_11-1)
[Sutter, Herb](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") (18 June 2017). ["P0707 R0 - Metaclasses"](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0707r0.pdf) (PDF). *open-std.org*. WG21. [Archived](https://web.archive.org/web/20201111204111/http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0707r0.pdf) (PDF) from the original on 11 November 2020. Retrieved 8 August 2018.
12. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-SutterMetaclasses2_12-0)**
[Sutter, Herb](https://en.wikipedia.org/wiki/Herb_Sutter "Herb Sutter") (12 October 2024). ["Declarative class authoring using consteval functions + reflection + generation (aka: Metaclasses for generative C++)"](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p0707r5.pdf) (PDF). *open-std.org*. WG21. Retrieved 14 December 2025.
13. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-13)**
Andrei Alexandrescu, Barry Rezvin, Daveed Vandevoorde (16 July 2024). ["Code Injection with Token Sequences"](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p3294r1.html). *open-std.org*. WG21.
`{{cite web}}`: CS1 maint: multiple names: authors list ([link](https://en.wikipedia.org/wiki/Category:CS1_maint:_multiple_names:_authors_list "Category:CS1 maint: multiple names: authors list"))
14. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-14)**
Michiaki Tatsubori (14 October 2007). ["OJ: An Extensible Java"](https://web.archive.org/web/20140813142000/http://www.csg.ci.i.u-tokyo.ac.jp/openjava/). *csg.ci.i.u-tokyo.ac.jp*. University of Tokyo. Archived from [the original](http://www.csg.ci.i.u-tokyo.ac.jp/openjava/) on 13 August 2014.
15. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-15)**
Shigeru Chiba (14 October 2007). ["OpenC++ Home Page"](https://web.archive.org/web/20140821053838/http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/openc++.html). *csg.ci.i.u-tokyo.ac.jp*. University of Tokyo. Archived from [the original](http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/openc++.html) on 21 August 2014.
16. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-16)**
Shigeru Chiba. ["Welcome to OpenC++"](https://opencxx.sourceforge.net/). *opencxx.sourceforge.net*. University of Tokyo. Retrieved 10 December 2025.
17. **[^](https://en.wikipedia.org/wiki/Metaclass#cite_ref-17)**
["An implementation of mixins in Java using metaclasses"](https://web.archive.org/web/20071016230949/http://csl.ensm-douai.fr/noury/uploads/1/nouryBouraqadi.Gpce03WorkshopOnRepls.pdf) (PDF). Archived from [the original](http://csl.ensm-douai.fr/noury/uploads/1/nouryBouraqadi.Gpce03WorkshopOnRepls.pdf) (PDF) on 16 October 2007. Retrieved 27 November 2007.
- [What Is a Metaclass?](http://www.atalon.cz/om/what-is-a-metaclass/) |
| Shard | 152 (laksa) |
| Root Hash | 17790707453426894952 |
| Unparsed URL | org,wikipedia!en,/wiki/Metaclass s443 |