Search code examples
c++polymorphism

It is referenced and I still get undefined reference issue


class base_rec { 
    public: 
        base_rec():str(" "){}; 
        base_rec(string contentstr):str(contentstr){}; 
        void showme() const; 
    protected: 
        string str; 
    
};

class u_rec:public base_rec {
    public:
        u_rec():base_rec("undergraduate records"){};
        void showme() { cout << "showme() function of u_rec class\t"
            << str << endl;}
     
};
class g_rec:public base_rec {
    public:
        g_rec():base_rec("graduate records"){};
        void showme() { cout << "showme() function of g_rec class\t"
            << str << endl;}
};

int main() {
 base_rec *brp[2];
 brp[1] = new u_rec;
 brp[2] = new g_rec;
 for (int i=0; i<2; i++) {
 brp[i]->showme();
 }
}

Error Message:

main.cpp:(.text+0x58): undefined reference to `base_rec::showme() const' collect2: error: ld returned 1 exit status.

How can I fix it! the showme() is defined in base_rec


Solution

  • There are 3 issues with your program. First the way you define an override in C++ is by making the function in base class pure virtual. Then you can override the implementation in child class. Since you are defining an array of base class type objects which has no definition, C++ assumes you want to call the functions of base class.

    The second issue is that the array indices are out of bound. There can't be an index 2 in an array of size 2.

    Lastly when you allocate memory on heap using new, you need to free it up as well, using delete. Failing to do this can lead to memory leaks.

    #include <string>
    using namespace std;
    
    class base_rec {
    public:
        base_rec():str(" "){};
        base_rec(string contentstr):str(contentstr){};
        virtual void showme() const=0;
        virtual ~base_rec(){};
    protected:
        string str;
    
    };
    
    class u_rec:public base_rec {
    public:
        u_rec():base_rec("undergraduate records"){};
        void showme() const { cout << "showme() function of u_rec class\t"
                             << str << endl;}
    
    };
    class g_rec:public base_rec {
    public:
        g_rec():base_rec("graduate records"){};
        void showme() const { cout << "showme() function of g_rec class\t"
                             << str << endl;}
    };
    
    int main() {
        base_rec *brp[2];
        brp[0] = new u_rec;
        brp[1] = new g_rec;
        for (int i=0; i<2; i++) {
            brp[i]->showme();
        }
        for (auto b: brp) {
            delete b;
        } 
    }