Is methods overriding in C++ always done in a derived class's header?
Sorry for the Noob question .I have been learning C++ for a while and from the book "Visual C++" by Ivor Horton I see that when extending some class the methods overriding is done in the header of 开发者_JS百科the derived class.I haven't found any example where it can be done in .cpp files.So my question is if the .cpp files can only contains the "native" methods of the current class?Or there is a way also to override parent methods there.
Method overriding is basically done to acheive polymorphic behavior wherein the Derived class re-implements the Base class methods suitable to its own use. So yes usually methods are overriden in dervied class.
By the way usually methods are declared in the header files and defined in the source files, So I am not sure what you exactly mean.
Probably, You should have a look at this,
What is the difference between a definition and a declaration?
I see that when extending some class the methods overriding is done in the header of the derived class.
Not essentially. Header is there for declarations and implementation can go in a source file. It doesn't matter even it is for polymorphic methods or native member functions.
You can use .h and .cpp as you wish. You can have both declaration and definition in both .h and .cpp's. Not that you should, but you can. cpp's are compiled by the compiler, if you include your .h in a cpp, it will also be compiled. So to answer your question, yes, you can override in the cpp.
Example:
A.h
class A{
public:
A() {};//definition and declaration in header
virtual void foo() {};
};
B.cpp
#include "A.h"
class B : public A{
public:
B() {};//definition and declaration in source file
virtual void foo() {};
};
int main()
{
A* pA = new B;
pA->foo(); //will call foo from B
return 0;
}
B will however only be visible in B.cpp
.
Don't do it thoguht!
精彩评论