Search code examples
c++inheritancevirtual

Why can't I acces the virtual function through an object call?


I am trying to do an OOP simulation of using a bank Card, just for practice, nothing too complex; I'm getting a strange error. The call is a little bit silly, but i was just trying to see if "read" function works ok, not to test it's real purpose. I don't understand why I get the error below, i know that i can acces a virtual method with an object directly, not necessarily with a pointer. Also, sorry for most of the members not being written in english. Here is my code:

#include <iostream>
#include <string>
using namespace std;

class Card
{

protected:
    string nrCard;
    string NumeDetinator;
    string data_expirare;
    int CVV;
    double credit;

    static unsigned nr_ord;

public:
    Card();
    Card(string nC, string ND, string d_ex, int cvv, double CRD);
    virtual getCredit(); //= 0;
    virtual void print(ostream&) const;//= 0;
    virtual void read(istream&) ;//= 0;
    virtual void print(ostream &) ;//= 0;
};

unsigned Card :: nr_ord = 0;

Card :: Card() : nrCard("XXXX - XXXX - XXXX - XXXX"), NumeDetinator("???? ????"), data_expirare("DD - MM - YY"), CVV(999), credit(0.0) {}
Card :: Card(string nC, string ND, string d_ex, int cvv, double CRD) : nrCard(nC), NumeDetinator(ND), data_expirare(d_ex), CVV(cvv), credit(CRD) {}

void Card::print(ostream& out) const {
    out << "numar card: " << this->nrCard << "\n";
    out << "Nume detinator: " << this->NumeDetinator << "\n";
    out << "data expirare: " << this->data_expirare << "\n";
    out << "CVV " << this->CVV << "\n";
    out << "Credit disponibil: " << this->credit << "\n";
}

void Card::read(istream& in) {
    cout << "Dati datele cardului:\n numar card: ";
    in >> this->nrCard;
    cout << "\nNumele detinatorului: ";
    in >> this->NumeDetinator;
    cout << "\nData expirarii: ";
    in >> this->data_expirare;
    cout << "\nCVV: ";
    in >> this->CVV;
    cout<< "\ncredit: ";
    in >> this->credit;
}

class Card_Standard : Card
{
    int limitaExtragere;
    double comisionDepasireLimita;
};

class Card_Premium : Card_Standard
{
  int m;
};


int main() {

Card C;

C.print(cout);  /// error: undefined reference to vtable for Card , id returned 1 exit status;


return 0;
}



Solution

  • "undefined reference to vtable" is compiler's way of saying "not all virtual methods are implemented".

    Implement all virtual members (or mark them pure) and the error will go away.

    BTW, virtual getCredit(); is missing a return type (probably double?).