Why base class function is called instead of derived one?
I have a class:
class ProjectService : public CProjectT<CSoapMSXMLInetClient>
{
...
}
I have implemented HRESULT ConnectToServer();
function in this derived class. Then I instantiated an object and called a function:
ProjectService project;
project.f1();
now, f1()
calls f2()
and f2()
calls ConnectToServer()
. All of those functions are members of CProjectT<CSoapMSXMLInetClient>
The problem here is, CProjectT<CSoapMSXMLInetClient>::ConnectToServer()
is called instead of ProjectService::ConnectToServer()
. (I have a debug b开发者_开发百科reakpoint on the first line of both ConnectToServer()
functions. The one in base class is hit.)
Why?
Make sure that the ConnectToServer function is defined with the keyword virtual
in the parent class.
Read about the virtual keyword in C++
As said, you need the keyword virtual
. Why? Because in your function f2()
, defined only in CProjectT
, you call the function CProjectT<CSoapMSXMLInetClient>::ConnectToServer()
. Without the virtual
keyword, there is no way to know for f2()
that the derived method should be called.
If you want to test :
#include <iostream>
using namespace std;
class Base
{
public:
void f(){g();} // Wants to call Base::g() if there's no "virtual" keyword
void g(){cout << "Base" << endl;}
// virtual void g(){cout << "Base" << endl;}
};
class Derived : public Base
{
public:
void g(){cout << "Derived" << endl;}
};
int main(int argc, char *argv[])
{
Derived d;
d.f();
}
f2() invokes ConnectToServer(), and the method f2() is defined at COMPILE TIME. since f2() is a part of CProject and NOT ProjectService, it have two possibilities:
1. invoke hard coded a none virtual function from CProject
2. invoke a function from the virtual table.
since ConnectToServer() is not virtual, the first option will be 'chosen' by the compiler.
like @Ozair said in the first comment (and his answer): putting the virtual keyword will make the function virtual and the compiler will 'choose' the second option, and derived class will be called.
(note that the function is called from f2(), so the compiler can't really tell if this instance is the base or derived)
精彩评论