Thread View: gnu.g++.lib.bug
1 messages
1 total messages
Started by Fred Richardson
Fri, 09 Oct 1992 21:10
Bug?
Author: 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.
Thread Navigation
This is a paginated view of messages in the thread with full content displayed inline.
Messages are displayed in chronological order, with the original post highlighted in green.
Use pagination controls to navigate through all messages in large threads.
Back to All Threads