It is my understanding that we can never instantiate an abstract class in C++
or equally an interface in Java
. This makes sense because we have "pure virtual" functions that provide no implementation, therefore we can only instantiate subclasses of this class/interface that adhere to the contract formed by the abstract class. Consider the following code:
#include <iostream>
#include <vector>
using namespace std;
class AbstractClass {
public:
AbstractClass() {
cout << "Instantiating" << endl;
}
virtual void pureVirtualFunction() = 0;
void testMe() {
cout << "test" << endl;
}
};
int main() {
vector<AbstractClass*> v;
v.resize(100);
cout << v.size() << endl;
v[0]->testMe();
v[0]->pureVirtualFunction(); //segfault on my machine
return 0;
}
What baffles me when I run this on my computer is that I can actually resize the vector. I always thought that std::vector::resize
instantiated some number of elements, thus calling each element's constructor but further research shows that the constructor is not actually called (also evident by my stdout not showing 100x "Instantiating" strings).
So if std::vector::resize
allocates space for these new objects, and allows me to actually call methods on each of them, how are they not fully instantiated? I figured I couldn't even call resize()
on a vector of abstract classes but I can, I assume because they are not fully initialized. Could someone explain what is happening here?
EDIT:
Brain fart..forgot that a vector of pointers, when resized, does not actually allocate new
elements, as pointers can be created without allocated elements behind them, however...why can I still call a member function on a pointer to a class in which is not instantiated?