Topic: Forward class declarations with different definitions


Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 16 Jan 1995 21:56:18 GMT
Raw View
geert@cs.ruu.nl (Geert-Jan Giezeman) writes:


>In a header file there is a forward declaration of a class, but not a full
>class description (class opaque in the example below).
>In two different files, two different definitions of this class are given. ...

>My compiler allows me to do this, but does the standard actually allow it?
>What I read in the ARM (May 1991 version) was rather vague about this.

The One-Definition Rule states that if you use different definitions
for the same thing in one program, the results are undefined.
"Undefined" means that any result at all is possible, and the compiler
does not have to diagnose the error. Don't do it.
--
Steve Clamage, stephen.clamage@eng.sun.com




Author: geert@cs.ruu.nl (Geert-Jan Giezeman)
Date: Mon, 16 Jan 1995 12:28:47 GMT
Raw View
Consider the following situation:
In a header file there is a forward declaration of a class, but not a full
class description (class opaque in the example below).
In two different files, two different definitions of this class are given.

The example below shows a situation where this can be handy.
An acces point in a data structure is returned, which can be used later on.

My compiler allows me to do this, but does the standard actually allow it?
What I read in the ARM (May 1991 version) was rather vague about this.


--- EXAMPLE ---

// file header.h

struct opaque;

typedef opaque *item;

struct base {
    virtual item insert(int key) = 0;
    virtual void remove(item) = 0;
};

class list: public base {
    item first;
public:
    item insert(int key);
    void remove(item);
};

class tree: public base {
    item root;
public:
    item insert(int key);
    void remove(item);
};


// file list.C
#include "header.h"

struct opaque {
    int info;
    item prev, next;
};

item list::insert(int key)
{
    item result = new opaque;
    // ...
    return result;
}

void list::remove(item it)
{
    // ...
    delete it;
}

// file tree.C
#include "header.h"

struct opaque {
    int info;
    item parent, left, right;
};

item tree::insert(int key)
{
    item result = new opaque;
    // ...
    return result;
}

void tree::remove(item it)
{
    // ...
    delete it;
}

--
Geert-Jan Giezeman, Dept of Computer Science, Utrecht University,
Padualaan 14, P.O. Box 80.089, 3508 TB Utrecht, The Netherlands.
Telephone: +31 30 534096
Telefax:   +31 30 513791   Email: geert@cs.ruu.nl