Question

So, based on a cursory search, I already know that calling a virtual function (pure or otherwise) from a constructor is a no go. I have restructured my code to ensure that I am not doing that. While this causes the user of my classes to add an extra function call in their code, this is really not that big of a deal. Namely, instead of calling the constructor in a loop, they now call the function which (in fact!) increases performance of the code since we don't have the housekeeping of building and destroying the object in question every time.

However, I have stumbled across something interesting...

In the abstract class I have something like this:

// in AbstractClass.h:
class AbstractClass {
 public:
  AbstractClass() {}
  virtual int Func(); //user can override
 protected:
  // Func broken up, derived class must define these
  virtual int Step1() = 0;
  virtual int Step2() = 0;
  virtual int Step3() = 0;
// in AbstractClass.cpp:
int AbstractClass::Func() {
  Step1();
  // Error checking goes here
  Step2();
  // More error checking...
  // etc...
}

Basically, there is a common structure that the pure virtual functions follow most of the time, but if they don't Func() is virtual and allows the derived class to specify the order. However, each step must be implemented in derived classes.

I just wanted to be sure that there's nothing that I necessarily am doing wrong here since the Func() function calls the pure virtual ones. That is, using the base class, if you call StepX(), bad things will happen. However, the class is utilized by creating a derived object and then calling Func() (e.g. MyDerivedObject.Func();) on that derived object, which should have all the pure virtual functions overloaded properly.

Is there anything that I'm missing or doing incorrectly by following this method? Thanks for the help!

Was it helpful?

Solution

Func is calling the virtual ones, not the pure virtual ones. You would have to qualify the calls with a scope operator, i.e. AbstractClass::Step1() to call THAT (virtual pure) function. Since you are not, you will always get an implementation by a derived class.

OTHER TIPS

A virtual function in a base class makes the derived classes able to override it. But it seems things stop there.

But if the base class virtual function is pure, that forces the derived classes to implement the function.

As a side comment you can make the Step1, Step2, Step3 methods private so that you'll be prevented by the compiler from directly calling them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top