Comparing With Structs
Similar to structs, classes are features for defining new types. By this definition, classes are user defined types. Different from structs, classes provide the object oriented programming (OOP) paradigm in D. The major aspects of OOP are the following:
Encapsulation: Controlling access to members (Encapsulation is available for structs as well but it has not been mentioned until this chapter.)
Inheritance: Acquiring members of another type
Polymorphism: Being able to use a more special type in place of a more general type
Encapsulation is achieved by protection attributes, which you will see in a later chapter. Inheritance is for acquiring implementations of other types. Polymorphism is for abstracting parts of programs from each other and is achieved by class interfaces.
This chapter will introduce classes at a high level, underlining the fact that they are reference types. Classes will be explained in more detail in later chapters.
Comparing with structs
In general, classes are very similar to structs. Most of the features that you have seen for structs in the following chapters apply to classes as well:
However, there are important differences between classes and structs.
Classes are reference types
The biggest difference from structs is that structs are value types and classes are reference types. The other differences outlined below are mostly due to this fact.
Class variables may be
As mentioned briefly in the null value and the is operator chapter, class variables can be null. In other words, class variables may not provide access to any object. Class variables do not have values themselves; the actual class objects must be constructed by the
As you should also remember, comparing a reference to null by the
== or the
!= operator is an error. Instead, the comparison must be done by the
is or the
!is operator, accordingly: