The code is pretty straight forward:
class SuperClass
{
public:
virtual void someMethod() = 0;
};
class SubClass : public SuperClass
{
public:
virtual void someMethod()
{
std::cout << "hello" << std::endl;
}
};
class CallerClass
{
public:
std::vector<SuperClass*> subClasses;
CallerClass()
{
subClasses.push_back(&SubClass());
}
void callMethods()
{
subClasses[0]->someMethod();
}
};
int main(int argx, char**argv)
{
CallerClass cc;
cc.callMethods();
return 0;
}
The problem occurs when I actually call try to call the subClass' 'someMethod()' in the CallerClass' 'callMethods()'. In Visual Studio, it simply breaks at that line of code without any explanation. I have solved the problem by changing push_back(&SubClass()) to push_back(new SubClass()).
I am curious as to why the latter works and not the former. I thought it was because an object created in a method will only exist within the method, and by using 'new', space was actually being allocated for that object after the function ended; but I added an int a = 1 to SuperClass and was able to access it using in a similar fashion to what's inside 'callMethods()'.
I must be missing some fundamental aspect of C++ here. Please inform me. Hopefully it's not something too obvious.