Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!uunet!rocket!dove From: dove@rocket.stars.flab.Fujitsu.JUNET (Webster Dove) Newsgroups: comp.lang.c++ Subject: cant use virtuals in base constructors Message-ID: Date: 4 May 89 13:31:13 GMT Sender: news@rocket.UUCP Distribution: comp Organization: Sanders Advanced Technology Dept. Lines: 97 Posting-Front-End: GNU Emacs 18.44.4 of Tue May 12 1987 on rocket (berkeley-unix) The following program prints base base base derived and I wish it would print base base derived derived This happens with cfront and g++ also. // -*- C++ -*- #include class base { public: virtual void foo() { cout << "base"; } base() { foo(); } }; class derived : base { public: virtual void foo() { cout << "derived"; } derived() {}; }; main() { base x; x.foo(); derived y; // Prints "base" should print "derived". y.foo(); } Consider the case of someone implementing a base class for others to use (e.g. an error handler). I wanted to use this technique to tell at construction time that a derived class had failed to implement its own method for something (e.g. type_string()). I would do this by invoking the virtual in the base constructor, and having a dummy method in the base class that I could detect. class base { public: virtual char *type_string() { return("(unknown)"); } base() { if(strcmp(type_string(), "(unknown)") == 0) { cerr << "Illegal derived class lacks a type_string() method\n"; abort(); } } }; In c++ 1.x I cannot achieve this at compile time with something equivalent to the (:required_methods 'type_string) construct in LISP flavors. I participated in the discussion about the lack of any compile time warning of the failure (due to some minor spelling or argument declaration error) of a derived method declaration to rendezvous succesfully with a base class virtual. The upshot was "make the base method a dummy that fails if it isn't overloaded by the derived". Well, I thought, since I can't detect this at compile time, I will invoke the afore mentioned method in the base constructor to check this early out rather than wait some indeterminate time for the program to call the method. I cannot achieve this at construction time since virtual methods don't behave as virtual methods in the base constructor (this is the intended behavior according to Michael Tiemann). Can someone suggest a straighforward way to do this? Will c++ 2.0 give me some capability to detect such coding failures gracefully? (Whatever happened to :required-methods, :before, :after, ...?) Web Dove P.S. Please reply to me via email as well, because I don't often get a chance to check the news. -- Dr. Webster Dove Computing Systems and Architectures Advanced Signal Processing Engineering (ASPEN) Dept. Sanders Associates (a Lockheed Company)