C++

0. Intended Use

C++ is a general-purpose object-oriented programming language, and isintended to be an improved C with object capabilties.

1. Basic Concepts

In C++, an object is a region of storage with associated semantics.In the context of the object model of C++, the term object refersto an instance of a class. A class defines the characteristics of its instancesin terms of members: data members (state) and member functions (methodsor operations), and the visibility of these members to other classes. C++is statically typed.

2. Objects

In C++, an object is a region of storage with associated semantics.The declaration int i;, specifies that iis an object of type int. In the context ofthe object model of C++, the term object refers to an instance ofa class. Thus a class defines the behavior of possibly many objects (instances).Objects are usually referred to by references, which are aliasesfor an object. "The obvious implementation of a reference is as a(constant) pointer that is dereferenced each time it is used." [Str92]

A C++ class definition generates a user-defined type. A class definesthe characteristics of its instances in terms of members: data members(state) and member functions (methods or operations), and the visibilityof these members to other classes. The class defines the form of all objectsthat belong to that class. Each object of the class that is created getsa copy of all the class data members, except for those declared as static(see entry under 2.6 state). All objects of a particular class sharethe member functions for that class.

2.1 Operations

Operations are defined by functions. In the context of the C++ objectmodel, functions may be globally defined (independently of object classes),or as part of class definitions (member functions). C++ essentially supportsa classical object model, in that member functions are associated withthe definition of a single object class. However, friend functionsmay be defined that, though not part of a class' definition, have accessto the internals of instances of that class. See entry under 5. Encapsulation.

2.2 requests

Class data members and member functions are accessed as if they wereelements of a data structure. A request for access is given by specifyingthe name of an object (e.g., a reference) and the name of the operation,together with the appropriate parameters.

2.3 messages

See 2.2 requests and 2.4 specification of behavioral semantics

2.4 specification of behavioral semantics

The behavior of a C++ object is defined by its member functions. (see2.1 Operations and 2.5 methods). A definition of a memberfunction specifies argument types and the result type. There is no formalspecification of the semantics of an operation; the semantics are specifiedby the code of the member function.

2.5 methods

The behavior of a C++ object is defined by its member functions.All objects of a particular class share the member functions for that class.Every member function for a class must be declared with a function prototypein the class declaration. This prototype lists the arguments for the memberfunction. C++ adds an additional argument, this, to the beginningof the argument list for every member function. The this argumentis a pointer to the individual object for which the member function isbeing called (and is similar in some respects to self in Smalltalk).The this argument is implicit; it does not have to be explicitlyincluded in the function's argument list, nor does it have to be providedwhen the function is called.

The keyword virtualpreceding a member function declaration indicates that the function canbe redefined in classes derived from the current class (subclasses). Avirtual member function for a class is called through a jump table associatedwith the class. This allows a derived class' member function to be correctlycalled even when the variable used to access it is declared as being ofa base type. Non-virtual member function calls are bound at compile time.The derived class member function can invoke the base class member functionif this is required.

The keyword staticpreceding a member function declaration indicates that the function hasno this pointer. Static member functions (for example) provide away to access static data members without needing an actual instance ofthe class (static data members are data members shared by all instancesof the class; these would be equivalent to the instance variables of aSmalltalk class object). A static member function can access nonstaticmembers of its class only if passed an instance of the class (using the. or ->member access operators to refer to the particular member).

2.6 state

The state of a C++ object is defined by its data members. Eachobject of the class that is created gets a copy of all the data members,except for those declared as static.static data members aredata members shared by all instances of the class; these would be equivalentto the instance variables of a Smalltalk class object.

2.7 object lifetime

The life-cycle for an object begins when it is created, and ends whenit is destroyed. In a C++ class definition, a member function with thesame name as the class is a constructor. This is a function whichis called automatically whenever an instance of the class is created. Constructorsare typically used to initialize the data members of the object to theirdefault state, but may also be used to allocate resources (memory, files,etc.). For any class, a number of constructor functions may be declared,each taking different types of arguments, providing different ways of initializinginstances. A default constructor for a class is a constructor ofthat class that can be called without any arguments. A default constructorfor a class will be automatically generated if no constructor has beenexplicitly declared for that class. A copy constructor for a classis a constructor that can be called to copy an object of that class (ithas a single argument of the corresponding type). A copy constructor iscalled when, for example, an argument object is passed by value to a function,or when an object is initialized with the value of another object. A copyconstructor for a class will be automatically generated if no copy constructorhas been explicitly declared for that class. A member function with thesame name as the class with a leading tilde (~) is a destructor.This is a function that is called automatically when the object is deleted.The destructor is typically used to deallocate any memory allocated forthe object (and may also release any other resources acquired during construction).Constructors and destructors are not required in class definitions.

There are several ways to create objects in a C++ program. One is todefine a variable as being of a particular class, either as a global variableor as a local variable within a block. When the declaration is encounteredduring program execution, space is allocated for the object and the constructor,if any, for the object is called. Similarly, when an object variable goesout of scope, its destructor is called automatically. Another way to createan object is to declare a variable that is a pointer to the object classand call the C++ new operator, which will allocatespace for the object and call the constructor, if any, for the object.In this case, the pointer variable must be explicitly deallocated withthe delete operator. The constructor for theobject is executed when new is called, andthe destructor is executed when delete is called.An object can also be constructed by the explicit use of a constructorin an expression.

When a class is derived from another class, it inherits its parent class'constructor and destructor. Parent constructors are invoked before derivedconstructors. Destructors are invoked in the opposite direction, proceedingfrom the derived class upward through its parent chain.

2.8 behavior/state grouping

C++ implements a classical object model. In C++, members, includingmember functions, of objects are regarded as belonging to individual objectsand their classes, and are accessed via the objects they belong to.

2.9 communication model

2.10 events

3. Binding

C++ supports both static and dynamic (run-time) binding of functioninvocations to object member functions, depending on how the member functionswere declared in class definitions. In dynamic binding, binding occursdepending on the dynamic type of the object whose member functionis being invoked. The correct operation for that object will be selectedautomatically by the run-time system. See also entries under 2.5 methodsand 4. Polymorphism.

4. Polymorphism

C++ supports polymorphism by allowing member functions defined in classesto be overridden with member functions having the same names (operatoroverloading), but different implementations, in derived classes (subclasses).In selecting the appropriate member function to call in response to a functioninvocation, C++ distinguishes between the static type of a referenceand the dynamic type of the object it refers to at a given point. The dynamic type must be a descendant of the static type. The invocationis type-checked based on the static type of the reference. If the functioncalled is a virtual member function, the member function associated withthe actual object pointed to is called dynamically at run time. If thefunction is non-virtual, the call will have been statically bound to themember function of the reference's class at compile time. See also entriesunder 7. Types and Classes and 8. Inheritance and Delegation.

5. Encapsulation

C++ provides three levels of protection for data members and memberfunctions within a class. The default protection level is private.A private data memberor member function cannot be accessed by any function that is not a memberfunction of that class. The next level of protection is protected.A protected data memberor member function is accessible only to other member functions of thatclass or from classes derived from that class. The least restrictive levelof protection is public.public data members andmember functions can be accessed by any other function. The protectionlevel of data members and member functions is specified in the member declarationsusing the keywords public,protected, or private.

public members of aC++ base class do not automatically become publicmembers of the derived class; the base class must be explicitly declaredas public to allow this.

Specified non-member functions may be given access to private or protectedparts of classes. These functions are specified using the friendkeyword, and may be globally defined functions or members of other classes.Whole classes may be declared as friends of another class, in which caseevery member of the friend class can access the private members of thespecified class.

6. Identity, Equality, Copy

C++ supports both value and reference semantics (and supports both variablesthat "contain" objects, and variables that contain pointers orreferences to objects). In reference semantics, assignment essentiallycopies a pointer (or reference) to the object. In value semantics, assignmentcopies the value itself. In C++, the assignment operator can be used tocopy the object itself, or a reference to the object can be created, andthen copied. (The C++ assignment operator itself can be overridden, butthe default meaning is to copy the object itself). By contrast, Smalltalkeffectively always uses reference semantics for assignment, using alternativeoperations (shallowCopy, deepCopy) for value semantics. [Str92] describesthe implementation of cloning, shallow copy, and deep copy operations inC++ using the basic facilities.

7. Types and Classes

In C++, an object is a region of storage with associated semantics.The declaration int i;, specifies that iis an object of type int. In the context ofthe object model of C++, the term object refers to an instance ofa class. Thus a class defines the behavior of possibly many objects (instances).Objects are usually referred to by references, which are aliasesfor an object.

A C++ class definition generates a user-defined type. A class definesthe characteristics of its instances in terms of members: data members(state) and member functions (methods or operations), and the visibilityof these members to other classes. The class defines the form of all objectsthat belong to that class. Each object of the class that is created getsa copy of all the class data members, except for those declared as static.All objects of a particular class share the member functions for that class.If a class data member is defined with the statickeyword, that data member is shared by all objects of that class (thereis only one copy of the static data member).

C++ is a statically-typed language (although it supports explicit castsand unions that allow type checking to be suspended). A class essentiallydefines a type, and a derived class (subclass) is effectively a subtype.If a variable is of a type A, then it may only refer to objects of classA or its derived classes (subclasses). When a subclass is declared, thosemembers which redefine members declared in a superclass must be declaredin a way that is consistent with the superclass declaration, in order tomaintain substitutability of subclass instances.

An example rectangle class definition [Wes90] is:

A class can be declared within another class; such a class is calleda nested class. The name of a nested class is local to its enclosingclass. A class can also be declared within a function definition; sucha class is called a local class. The name of a local class is localto its enclosing scope.

An abstract class is a class that can be used only as a baseclass of some other class; no objects of an abstract class can be createdexcept as objects representing a base class of a class derived from it.Abstract classes support the notion of a general concept, such as shape,of which only more concrete variants, such as circleand square, can actuallybe used. An abstract class can also be used to define an interface forwhich derived classes provide a variety of implementations [Str92].

A class is abstract if it has at least one pure virtual function.Specifying a function in a base class as virtualmeans that if a derived class contains a function with the same name andhaving the same type, a call of that function for an object of the derivedclass always invokes the function in the derived class, even though theinvocation was through a pointer or reference to the base class. In thiscase, the derived class function is said to override the base classfunction. A virtual function is specified pure by specifying itsimplementation as =0 inthe function declaration in the class declaration.

C++ class templates provide a parameterized type facility (genericity).A class template specifies how individual classes can be constructed. Forexample, an example vector class template [Str92] might be:

The prefix template<class T>specifies that a template is being declared and that a type name Twill be used in the declaration (i.e., that vector is a parameterized typewith T as its parameter).A class generated from a class template is called a template class.Examples might be vector<int>,vector<complex>,etc. Such names can be used in the same way as the names of ordinary classes.

8. Inheritance and Delegation

C++ supports multiple inheritance. Inheriting classes are called derivedclasses, and the classes they inherit from are called base classes.The derived classes inherit all the data members and member functions fromthe base class. The derived class may extend the base class by addingnew data members or member functions. The derived class may also overridemember functions from the base class by supplying a new definition forthe function.

There are two forms of derivation, public and private.When the declaration of a derived class contains the keyword publicpreceding the base class name, objects of the derived class can be treatedas if they were instances of the base class. In particular, an object ofthe derived class can be used to invoke member functions or access datamembers defined for the base class. If the publickeyword is omitted, then the class is privately derived by default, andobjects of the derived class cannot be used as if they were objects ofthe base class. For privately derived classes, only those data membersand member functions that are defined (or overridden) in the derived classcan be accessed. Member functions of a privately derived class can accessthe base class's data members and member functions, but users of objectsof the derived class cannot used the derived objects to access data membersand member functions of the base class. In other words, public inheritanceis used to define subtypes (which can also share behavior), while privateinheritance allows sharing of behavior, but does not permit an instanceof the derived class to be used in situations where a base class instancewould be expected.

For example, given a rectangle class [Wes90]:

a round cornered rectangle might be defined as:

A class may be derived from any number of base classes. The order ofderivation is not significant except possibly for default initializationby constructor, for cleanup, and for storage layout. The order in whichstorage is allocated for base classes is implementation dependent. Accessto base class members must be unambiguous. Ambiguities can be resolvedby qualifying a name with its class name [Str92].

9. Noteworthy Objects

9.1 relationships

9.2. attributes

Attributes correspond to data members in C++. C++ data members may bepublic, and therefore visible at object interfaces.

9.3 literals

C++ supports all the value types provided by C, in addition to objects(instances of classes).

9.4 containment

A data member of an object class can be defined as having a type thatis either a type defined by an object class (in which case it will containan actual object) or a type that is a reference to an object class, e.g.,as being either type X or type X* (a pointer) or X& (a reference).A class can be declared within another class; such a class is called anested class. The name of a nested class is local to its enclosingclass. A class can also be declared within a function definition; sucha class is called a local class. The name of a local class is localto its enclosing scope.

9.5 aggregates

C++ supports C aggregate types (arrays, structs, and unions) in additionto (object) classes. A C++ struct is considered as a class without defaultaccess restrictions. Additional aggregate types can be defined using classtemplates. See 7. Types and Classes.

9.6 other

See 7. Types and Classes.

10. Extensibility

10.1 dynamic

10.2 metaclasses/metaobject protocol

C++ has no built-in concept of metaclasses or a metaobject protocol.An example of an extended C++ providing metaobject protocol capabilitiesis described in [CM93].

10.3 introspection

A C++ class is a compile-time entity which defines the form of all objects(instances) of the class. Classes have no explicit representation as objectsat run time. A run time type information (RTTI) facility recently addedto the C++ standard provides some support for introspection. This facilitydefines a typeid operatorwhich, given an expression as an argument, returns a reference to a system-maintainedobject of type Type_infocorresponding to the type of the argument. A Type_infoobject can be compared with another Type_infoobject to determine type equality or inequality, and its namemember function can be called to access the type's name. However, thereare limitations on the use of Type_infoobjects (e.g., they cannot be passed as function arguments), so they arenot fully equivalent to run time class objects.

11. Object Languages

12. Semantics of Base Classes (+type constructors)

13. Background and References

[Cli93] Marshall Cline, Frequently-Asked-Questions for comp.lang.c++,September, 1993.

[Cook90] Stephen Cook, "Programming Languages Based on Objects",in G. Blair, J. Gallagher, D. Hutchison, and D. Shepherd (eds.), Object-OrientedLanguages, Systems, and Applications, unpublished manuscript, 1990.

[CM93] S. Chiba and T. Masuda, "Designing an Extensible DistributedLanguage with a Meta-Level Architecture", in O. Nierstrasz, ed., ProceedingsECOOP '93, Lecture Notes in Computer Science 707, Springer-Verlag,July 1993, 483-502.

[Ste94] A. Stevens, "Patterns, New C++ Features, and OS/2",Dr. Dobb's Journal, Sept. 1994, 107-111.

[Str92] Bjarne Stroustrup, The C++ Programming Language, Second Edition,Addison-Wesley, 1992.

[Wes90] Dan Weston, Elements of C++ Macintosh Programming, Addison-Wesley,1990.

features matrixintro page