-2

For the following code,

class A
{
    private:
        virtual void f() = 0;
        virtual void g() = 0;
        ...

    public:
        A()
        {
        }

        ...
}

class B : public A
{
    private:
        void f()
        {
            ...
        }
        void g()
        {
            ...
        }
        void h()
        {
            if (...)
            {
                f();
            }
            else
            {
                g();
            }
        }

        ...

    public:
        B()
        {
            h();
        }

        ...

}


class C : public A
{
    private:
        void f()
        {
            ...
        }
        void g()
        {
            f();
        }
        void h()
        {
            if (...)
            {
                f();
            }
            else
            {
                g();
            }
        }

        ...

    public:
        C()
        {
            h();
        }

        ...

}

is there a way to avoid repetition of h() (the context of function h() in both classes B and C is the same) or we cannot avoid it simply because we cannot call pure virtual functions in constructors?

Kudayar Pirimbaev
  • 1,292
  • 2
  • 21
  • 42

2 Answers2

2

You can implement your function h() as a member of A.

The pure virtual function call would only be an issue if h() gets executed during the body of A::A() (or other A constructors or A::~A()). Inside the body of B::B() or C::C(), the polymorphic type of *this is B or C respectively, so your virtual overrides declared in class B or C will have effect.

aschepler
  • 70,891
  • 9
  • 107
  • 161
0

Sure, add an intermediate class D which only implements that function and inherits from A. Then B and C can inherit from D.

Cramer
  • 1,785
  • 1
  • 12
  • 20