Why do I need to refer an object of an inherited class through a pointer to its base class, when I am aware that the call to a function, exclusive to the inherited class, will produce a compilation time error?
Why Polymorphism?
Edit:
Here's a small piece of code as an example:
enum Suit { Spade, Heart, Club, Diamond };
enum Val { Ace=1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King };
class Card {
private:
Val val;
Suit suit;
public:
Card(Val val, Suit suit) : val(val), suit(suit) {
cout << "Card constructor called" << endl;
}
int get_val() { return val; }
Suit get_suit() { return suit; }
};
class BlackJackCard : public Card {
public:
int garbage;
BlackJackCard(Val val, Suit suit) : Card(val, suit), garbage(9) {}
int get_val() {
Val tmpVal = (Val)Card::get_val();
if(tmpVal == 1) return 11;
if(tmpVal < 10) return tmpVal;
return 10;
}
int exclusive_to_BJC() {
cout << "I do nothing!! and the garbage value my object holds is " << garbage << endl;
}
};
int main() {
Card *newCard = new BlackJackCard(King,Spade);
cout << newCard->get_val() << endl; // 13
cout << newCard->get_suit() << endl; // 0
/*Why should I use a base class referencing if I can't access all the*/
/*members of the object I have constructed(except for the virtual functions).*/
// cout << newCard->exclusive_to_BJC() << endl;
// cout << newCard->garbage << endl;
BlackJackCard *new_bjCard = new BlackJackCard(King,Spade);
cout << new_bjCard->get_val() << endl; // 10
cout << new_bjCard->get_suit() << endl; // 0
cout << new_bjCard->exclusive_to_BJC() << endl;
}