Zyneak Zyneak - 2 months ago 7
C++ Question

Inheriting And Using a Derived Function

I need to have a derived class call its new function as seen below. I've tried lots of different variants and positions of keywords.

I create a Base class with two methods PreLoad and Load. The point of PreLoad being to load things that always need to be loaded while Load is used for a class to load what it needs to function.

class Base
{
public:
Base();
void PreLoad();
virtual void Load();
};

Base::Base() {
PreLoad();
}

void Base::PreLoad() {
Load();
}

class Derived : public Base {
public:
virtual void Load() {
std::cout << "Hia" << std::endl;
}
};

int main()
{
Derived d = Derived();
d.PreLoad();
return 0;
}

Answer

Your code is lacking an implementation for Load in the base class. You have two options here:

  • Make Load() pure virtual - this option is good when subclasses must override Load(). Demo.
  • Provide a default implementation for Load() - this option is good when classes have an option of overriding Load(), but a default implementation is there. Demo.