Article View: gnu.g++.lib.bug
Article #290Bug?
From: Fred Richardson
Date: Fri, 09 Oct 1992 21:10
Date: Fri, 09 Oct 1992 21:10
92 lines
2635 bytes
2635 bytes
I think I've found a bug which occurs when virtual functions are
overriden and called by the construction routine. It looks like if a
virtual function is over riden by a derived class and it is called in the
base classes constructor then only the base classes implementation of the
virtual function will be called.
Here's a long example
(sorry, I could think of a shorter one):
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/******************************************************************************
This is a test of virtual function overriding.
******************************************************************************/
#include <stdlib.h>
#include <String.h>
#include <string.h>
class base
{
public:
base(char* astr);
virtual char* testVirtual();
void test();
protected:
char* theStr= NULL;
};
class derived : public base
{
public:
derived(char* astr);
char* testVirtual(); // Over-ridden virtual function
};
base::base(char* astr)
{
theStr = strdup(astr);
test(); // call during initialization
}
char* base::testVirtual()
{
String s = theStr;
s = "base class: " + s + "\n";
return(s);
}
void base::test()
{
cout << testVirtual();
}
derived::derived(char* astr) : base(astr)
{
}
char* derived::testVirtual()
{
String s = theStr;
s = "derived class: " + s + "\n";
return(s);
}
int main(int argc, char *argv[])
{
if (argc < 2)
return(0);
cout << "Here's the output during construction:\n";
derived d(argv[1]);
cout << "Here's the output after construction:\n";
d.test();
return(0);
}
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Here's the ouput from the shell when running the programming:
mynah:54> test_virt "Hello World"
Here's the output during construction:
base class: Hello World
Here's the output after construction:
derived class: Hello World
mynah:55>
So as you can see, the derived classes virtual function is called during
initialization. This is a serious limitation, especially if one wants to
allocate things differently during construction.
Technical Details
Message-ID:
<FREDR.92Oct9171037@mynah.bu.edu>Path:
arc1-ca.pugleaf.net!sparky!uunet!usc!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!raven.bu.edu!fredrShow Full Headers
Complete Article Headers
Newsgroups: gnu.g++.lib.bug Path: arc1-ca.pugleaf.net!sparky!uunet!usc!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!raven.bu.edu!fredr From: fredr@raven.bu.edu (Fred Richardson) Subject: Bug? Message-ID: <FREDR.92Oct9171037@mynah.bu.edu> Sender: gnulists@ai.mit.edu Organization: I can do that too !!! Distribution: gnu Date: Fri, 9 Oct 1992 21:10:37 GMT Approved: bug-lib-g++@prep.ai.mit.edu Lines: 93