This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Re: Question about inheritance
- To: "Peter V. Evans" <pevans at enteract dot com>
- Subject: Re: Question about inheritance
- From: Noel Yap <nyap at garban dot com>
- Date: Tue, 04 Aug 1998 08:01:08 -0400
- CC: egcs at cygnus dot com
- Organization: Garban LLC
- References: <Pine.BSF.3.96.980803155026.21336A-100000@adam.enteract.com>
Peter V. Evans wrote:
>
> Hi,
>
> I'm developing a program which makes heavy usage of inheritance. Let me
> give the example first:
>
> class foo
> {
> public:
> typedef int hi;
>
> void doit (void)
> {
> if (sizeof(hi) == sizeof(int))
> puts("int");
> else
> puts("something else");
> }
> };
>
> class stuff : public foo
> {
> public:
> typedef double hi;
> };
>
> int
> main (void)
> {
> stuff s;
>
> s.doit(); // Prints out "int", not "something else"
> return 0;
> }
>
> ---
>
> The function doit, thus, does not see the derived class' "hi", only the
> parent class. I couldn't say if this is the correct behaviour, since I
> don't know C++ as well as most others, but a better question would be,
> how to get doit to somehow see the derived class "hi" instead of the
> parent class "hi"?
A better question is, "Do you really want to do this?" Bertrand Meyer
introduced (though he may not have invented) the concept of "Design by
Contract." In short, the concept says that functions and classes have a
set of preconditions (ie system states that users must meet) and
postconditions (ie system states that the class or function must
satisfy). When using inheritence, one must not break the contract set
by the parent class. This means that subclasses can only make
preconditions stricter and postconditions more relaxed. (Come to think
of it, a natural consequence would be that inheritence hierarchies
should not be that deep). IMHO, the above overriding of hi will break
the contract.
To answer your original question, you cannot do what you want to do
without using templates.
Noel