PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : C++ Polymorphie


The_Invisible
2011-04-10, 09:20:07
Hallo,

irgendwie stehe ich gerade auf der Leitung bei einem wahrscheinlich einfachen Problem.

Das Problem ist folgendes: Ich habe eine Basisklasse, davon eine abgeleitete Klasse und will von der Basisklasse eine Methode der abgeleiteten Klasse aufrufen.

Sieht folgendermaßen aus mit den relevanten Codeschnipseln:

Basisklasse:

class MikrotikAPI
{
public:
MikrotikAPI();
MikrotikAPI(const std::string &strIpAddress, const std::string &strUsername, const std::string &strPassword, int port);
virtual ~MikrotikAPI();

protected:
virtual void Connect(const std::string &strIpAddress, int port);
}

MikrotikAPI::MikrotikAPI(const string &strIpAddress, const string &strUsername, const string &strPassword, int port)
{
Connect(strIpAddress, port);

...
}

void MikrotikAPI::Connect(const string &strIpAddress, int port)
{
struct sockaddr_in address;
int connectResult;
int addressSize;

...
}



Abgeleitete Klasse:

class StyMikrotikAPI : public MikrotikAPI
{
public:
StyMikrotikAPI();
StyMikrotikAPI(const QString &strIpAddress, const QString &strUsername, const QString &strPassword, int port);
virtual ~StyMikrotikAPI();

protected:

void Connect(const std::string &strIpAddress, int port);
};

StyMikrotikAPI::StyMikrotikAPI(const QString &strIpAddress, const QString &strUsername, const QString &strPassword, int port)
: MikrotikAPI(strIpAddress.toStdString(), strUsername.toStdString(), strPassword.toStdString(), port)
{
...

std::cout << "new construct" << std::endl;
}

void StyMikrotikAPI::Connect(const std::string &strIpAddress, int port)
{
...

std::cout << "new connect" << std::endl;
}



Nehmen wir hier mal die Methode Connect(). Ich erzeuge ein Objekt der Klasse StyMikrotikAPI und gehe eigentlich davon aus das die Methode Connect() von der Klasse StyMikrotikAPI aufgerufen wird, ist aber nicht so, es wird die Methode von MikrotikAPI aufgerufen.

Bitte um Hilfe, ich check heute nix mehr anscheinend ;D

mfg

Markus89
2011-04-10, 09:44:58
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.

Von hier (http://www.artima.com/cppsource/nevercall.html).