πŸš€ go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: de.comp.lang.c++
Article #576

Wiedermal: Virtuelle Methoden

#576
From: Roman 'RoB' Bartke
Date: Sun, 15 Oct 1995 10:47
57 lines
2011 bytes
Meine lieben VIRTUosen!

Gegeben sei folgender Programmrumpf, bei dem das Verhalten der 
ShowError-Methode des Clients durch Vererbung modifiziert werden soll.
Das Connect() simuliert hierzu immer einen Fehler.


c.cc:
------------------------------------------------------------------------
#include <iostream.h>

class Client
{
public:
	Client() { Connect(); }
	virtual ~Client() { }
	void Connect() { ShowError(); }
protected:
	virtual void ShowError() { cerr << "Client::ShowError()\n"; }
};

class SpecialClient : public Client
{
public:
	SpecialClient():Client() { }
protected:
	void ShowError() { cerr << "SpecialClient::ShowError()\n"; }
};

int main(int argc, char *argv[])
{
	SpecialClient client;
	client.Connect();
	return 0;
}
------------------------------------------------------------------------

"g++ -Wall -o c c.cc -lg++; c" liefert:
Client::ShowError()
SpecialClient::ShowError()

Ich hΓ€tte hier
SpecialClient::ShowError()
SpecialClient::ShowError()
erwartet, da es beidemale um einen SpecialClient ging.

Warum ruft der Konstruktor nicht die neue virtuelle Methode auf, 
sondern noch die alte? 

Das ist im Beispiel tragisch, da der Konstruktor bei neudefinierten
virtuellen Methoden nicht automatisch "connecten" darf...

Wo kann man die Antwort darauf ggf. nachlesen?

-- 
  eMail: rob@robot.mayn.de; rob@informatik.uni-wuerzburg.de          PGP on
 whoami: main(i){putchar(471252544>>i*5&31|!!(i%6)<<6)&&main(++i);}  demand
Technical Details
Message-ID: <45qosk$t10@robot.mayn.de>
Path: arc1-ca.pugleaf.net!robot.mayn.de!not-for-mail

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!robot.mayn.de!not-for-mail
From: rob@robot.mayn.de (Roman 'RoB' Bartke)
Newsgroups: de.comp.lang.c++
Subject: Wiedermal: Virtuelle Methoden
Date: 15 Oct 1995 11:47:48 +0100
Organization: RoBot
Message-ID: <45qosk$t10@robot.mayn.de>
NNTP-Posting-Host: robot.mayn.de
Mime-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 8bit
X-Copyright: No distribution outside "Usenet news" without prior permission from the author.
X-Newsreader: STRN v0.9.3.1pre