see comments. set me straight. many, many thanks...
3 questions about inheritance, pointers, & polymorphism
#include <iostream>
using namespace std;
class baseClass {
public:
void nVirt() {
cout << "not virtual, base " << endl;
}
virtual void yVirt() {
cout << "virtual, base " << endl;
}
};
class derivedClass : public baseClass {
public:
void nVirt() {
cout << "not virtual, derived " << endl;
}
virtual void yVirt() {
cout << "virtual, derived " << endl;
}
};
int main()
{
baseClass someBase; //base obj
baseClass * basePtr; //base obj pointer
derivedClass someDerived; //derived obj
derivedClass * derivedPtr; //derived obj pointer
basePtr = &someBase; //set base obj pointer to base obj
basePtr->nVirt(); //as expected
basePtr->yVirt(); //as expected
basePtr = &someDerived; //set bas obj pointer to derived obj
basePtr->nVirt(); //????
/*
why does a pointer of base type still call base methods when it is
pointing to the address of a derived obj? do base obj pointers
always point to base methods even when pointing to derived obj's?
*/
basePtr->yVirt(); //????
/*
why should i be surprised that same pointer is calling the yvirt
function since it is pointing to a derived object? shouldn't a
pointer to a derived object also point to that object's members?
*/
derivedPtr = &someBase; //ERROR????
/*
i've read that a pointer to derived obj can point to a
base obj. why not here? what gives?
*/
return 0;
}