One Definition Rule - Examples

Examples

In general, a translation unit shall contain no more than one definition of any class type. In this example, two definitions of the class type C occur in the same translation unit. This typically occurs if a header file is included twice by the same source file without appropriate header guards.

class C {}; // first definition of C class C {}; // error, second definition of C

In the following, forming a pointer to S or defining a function taking a reference to S are examples of legal constructs, because they do not require the type of S to be complete. Therefore, a definition is not required.

Defining an object of type S, a function taking an argument of type S, or using S in a sizeof expression are examples of contexts where S must be complete, and therefore require a definition.

struct S; // declaration of S S * p; // ok, no definition required void f(S&); // ok, no definition required void f(S); // ok, no definition required S f; // ok, no definition required S s; // error, definition required sizeof(S); // error, definition required

Read more about this topic:  One Definition Rule

Famous quotes containing the word examples:

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)

    No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.
    André Breton (1896–1966)

    It is hardly to be believed how spiritual reflections when mixed with a little physics can hold people’s attention and give them a livelier idea of God than do the often ill-applied examples of his wrath.
    —G.C. (Georg Christoph)