i'm using vector for the first time in c++ and my problem is to call different overridden methods, let me explain: I got the CARD class subclassed by SPECIALCARD. In CARD there is a method printCard() and in SPECIALCARD the method is overridden. Then in the main i create a vector of Card. I put in the first position a card and in the second position a specialcard. When i try to call the printCard() method on the first and the second position it always run the method of the parent (but i want to call the parent method in first position and the son method in the second position). Here is the Card class:
CARD.H
using namespace std;
class Card
{
public:
Card(int number, string seed);
virtual void printCard();
protected:
int number;
string seed;
};
CARD.CPP
#include "Card.h"
#include <iostream>
#include <string>
using namespace std;
Card::Card(int number, string seed)
{
this->number = number;
this->seed = seed;
}
void Card::printCard()
{
cout << "the card is " << number << " of " << seed << endl;
}
And here is the SpecialCard class
SPECIALCARD.H
#include "Card.h"
#include <string>
using namespace std;
class Special_Card : public Card
{
public:
Special_Card(int number, string name, string seed);
string getName();
virtual void printCard();
private:
string name;
};
SPECIALCARD.CPP
#include <iostream>
#include "Special_Card.h"
#include "Card.h"
#include <string>
using namespace std;
Special_Card::Special_Card(int number, string name, string seed): Card(number, seed)
{
this->number = number;
this->name = name;
this->seed = seed;
}
//overridden method
void Special_Card::printCard()
{
cout << "the card is " << name << " of " << seed << endl;
}
finally we got the main where i create the vector
#include <iostream>
#include "Card.h"
#include "Special_Card.h"
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <Card> deck;
deck.push_back(Card(1,"hearts"));
deck.push_back(Special_Card(10,"J","hearts"));
deck[0].printCard();
deck[1].printCard();
}
The console output is the card is 1 of hearts /n the card is 10 of hearts (in the second i want to print "the card is a J of hearts")