Virtual functions (undefined reference for vtable )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//Early and Late binding

#include<iostream>
using namespace std ;

class klm {
    public :

    void getdata(){
        cout << "Enter name ";
        cin >> name ;
        cout << "Enter age ";
        cin >> age ;
    }

    virtual void display();
    char name[20];
    int age ;
};


class mno : public klm {
   public :
    void getdata();
    void display(){
        cout << "\n Name of the person " << name  ;
        cout << "\n Age of the person " << age ;
    }
};

int main() {
 class klm *ref ;
 class mno obj;
 ref= &obj;
 ref->getdata();   // static binding or early binding
 ref->display();   // late binding or dynamic binding
 return 0 ;
}


An error keeps coming
"undefined reference to vtable for klm "
any ideas ?

btw I use codeblocks IDE with mingw compiler ..
Last edited on
Seeing as you did not define display as a pure virtual function it is looking for the body of display in the klm class and isn't finding it.

You will want to change line 16 to
virtual void display()=0;
which will make it a pure virtual function.

What this basically means is that the classes that inherit from klm will be able to create their own function based off of the display function but it can not be used directly in that class. (Or you could just add a blank body for it in the klm class but that's a waste).

Examples of this are shown here.
http://www.cplusplus.com/doc/tutorial/polymorphism/
Last edited on
you did not define the function display and you expect it to work. You must implement it before it can work

replace:

 
    virtual void display();


with:

 
  virtual void display(){}//<-pre-implement here and redefine in child class later 


or do what the poster above me said if you intend on implementing the virtual function in a child class, (you will have no choice if you do).

read up here on the site before you post your code.
Last edited on
thanks guys !!
well , I made the changes in the code and it worked .
It made some things clear that either a virtual function must have a body(can be a blank one too) and redefined in child class OR it must be declared as pure virtual function and defined in the child class later .
Topic archived. No new replies allowed.