Thursday, June 15, 2006

Bug of the week - 15 june 2006

Well this blog will be a bit techie one!!

There was a certain problem I faced while compiling a small cpp test code.
Whacked my brains for 3hrs to find this small bug!!
maybe a pro would have found it earlier!!

but here goes the problem!!


1 #include < iostream>
2
3 using namespace std;
4
5 class A {
6 public:
7 A( int a ): x( a ) {}
8 int getX() const { return x; }
9 void setX( int a ) { x = a; }
10 virtual void abc( void );
11 virtual ~A() {}
12 protected:
13 int x;
14 };
15
16 class B : public A {
17 public:
18 B( int a ) : A( a ) {}
19 void abc ( void ) { cout << "its B" << endl; }
20 ~B() { cout << "ending B" << endl; }
21 };
22
23 class C : public A {
24 public:
25 C( int a ) : A( a ) {}
26 void abc ( void ) { cout << "its C" << endl; }
27 ~C() { cout << "ending C" << endl; }
28 };
29
30 int main() {
31 B b = B( 1 );
32 C c = C( 2 );
33 cout << "b is : " << b.getX() << " C: " << c.getX() << endl;
34 b.abc();
35 c.abc();
36 return 0;
37 }

Now when compiled with g++ the code gives the following lonker error!!
/tmp/ccQfBUdf.o(.gnu.linkonce.t._ZN1AD2Ev+0xb): In function `A::~A()':
: undefined reference to `vtable for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.t._ZN1AC2Ei+0x8): In function `A::A(int)':
: undefined reference to `vtable for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.r._ZTI1B+0x8): undefined reference to `typeinfo for A'
/tmp/ccQfBUdf.o(.gnu.linkonce.r._ZTI1C+0x8): undefined reference to `typeinfo for A'
collect2: ld returned 1 exit status


Now for the bug!!

Well it was a small issue...
You ought to give a dummy implementation of virtual function abc at line 10 as



10 virtual void abc( void ){} or
10 virtual void abc( void ) = 0; make it a pure virtual function...

it will compile as a charm!!

Happy coding!!