Here are the classes:
BaseClass.h
BaseClass.cppCode:class BaseClass { public: BaseClass(); virtual ~BaseClass(); virtual void printStuff() const; protected: private: };
DerivedClass.hCode:BaseClass::BaseClass() { //ctor } BaseClass::~BaseClass() { //dtor } void BaseClass::printStuff() const { std::cout << "BaseClass" << std::endl; }
DerivedClass.cppCode:class DerivedClass : public BaseClass { public: DerivedClass(); virtual ~DerivedClass(); virtual void printStuff() const; protected: private: };
And here's main():Code:DerivedClass::DerivedClass() { //ctor } DerivedClass::~DerivedClass() { //dtor } void DerivedClass::printStuff() const { std::cout << "DerivedClass" << std::endl; }
When I call printStuff, the DerivedClass's function gets called. Now, if I remove the const part from the DerivedClass's printStuff function, we call the BaseClass's printStuff function. Can anyone explain why this happens? I tried a Google search, but not quite sure how to word this.Code:int main() { DerivedClass* aDC = new DerivedClass(); vector<BaseClass*> aVec; aVec.push_back( aDC ); aVec[0]->printStuff(); delete aDC; return 0; }


Reply With Quote
Bookmarks