I have come across a case as described below, and want to understand how this works. I have a class whose constructor expects another class as an argument. Then in code I see instead of passing that expected class’ object as an argument, instead another class’ object is passed (this class happens to be the base class for the expected class).
adding real code:
class s_api {
public:
};
class PB {
public:
PB ( s_api *sa ) {}
};
class TValue : public s_api {
public:
TValue () {}
};
int main() {
TValue tvl;
PB pb(tvl); //tvl is object of class TValue
}
How does this work)?
This is the basis of polymorphism. Wherever you have something that expects an
s_api *(i.e. a pointer to base class), you are free to pass aTvalue *(i.e. a pointer to derived class).