I am new to C++ and I am trying to play around with interface and its implementation. The Container
is supposed to be an interface while Vector
is its implementation. I am getting an error during the linking phase of the following c++ file. It is a single file Vector.cpp
as shown below:
#include<iostream>
using namespace std;
class Container {
public:
virtual int size() = 0;
virtual double& operator[](int) = 0;
virtual ~Container();
};
class Vector: public Container {
private:
double *elem;
int sz;
public:
Vector(initializer_list<double> lst):
elem {new double[lst.size()]}, sz {static_cast<int>(lst.size())} {
copy(lst.begin(), lst.end(), elem);
}
int size() {
return sz;
}
double& operator[](int i) {
return elem[i];
}
~Vector() {
cout << "Deallocating elem array\n";
delete[] elem;
}
};
Vector buildVector() {
Vector v = {1, 3, 5, 6};
return v;
}
int main() {
Vector v = buildVector();
for(int i = 0; i < v.size(); ++i) {
cout << v[i] << "\n";
}
cout << "Finishing main\n";
}
When I compile the code I get the following error that seems to be coming from the linker ld
:
$ g++ -std=c++11 Vector.cpp
/tmp/ccLibNob.o: In function `Container::Container()':
Vector.cpp:(.text._ZN9ContainerC2Ev[_ZN9ContainerC5Ev]+0x9): undefined reference to `vtable for Container'
/tmp/ccLibNob.o: In function `Vector::Vector(std::initializer_list<double>)':
Vector.cpp:(.text._ZN6VectorC2ESt16initializer_listIdE[_ZN6VectorC5ESt16initializer_listIdE]+0xc4): undefined reference to `Container::~Container()'
/tmp/ccLibNob.o: In function `Vector::~Vector()':
Vector.cpp:(.text._ZN6VectorD2Ev[_ZN6VectorD5Ev]+0x4c): undefined reference to `Container::~Container()'
/tmp/ccLibNob.o:(.rodata._ZTI6Vector[_ZTI6Vector]+0x10): undefined reference to `typeinfo for Container'
collect2: error: ld returned 1 exit status