abstract class with virtual base class and non default constructor

Discussion in 'C++' started by Marcel Müller, Mar 15, 2014.

  1. Virtual base classes are always constructed by the most derived class.
    So why need an abstract class a call to the constructor of it's virtual

    #include <stdio.h>

    class V
    V(int i) { printf("V::V(%i)\n", i); }

    class A : public virtual V
    A() : V(42) {} // <-- required to keep the compiler happy
    virtual void PureFunc() = 0;

    class D : public A
    D(int i) : V(i) {}
    void PureFunc() {}

    int main()
    { D d(7);

    From my understanding the constructor call V(42) could never be
    executed, isn't it? A cannot be instantiated and any class inheriting
    from A must initialize V::V(int) explicitly.

    Marcel Müller, Mar 15, 2014
    1. Advertisements

  2. I think making such a distinction between an abstract class and
    non-abstract class would be too much for an average compiler. After
    all, it might not be so obvious. For instance, the abstractness can be
    inherited (and not direct like in your 'A'), or it the inability to
    instantiate could be due to some other feature (and not a pure virtual
    function). And with conditions like that the standard would be too

    Or it might be just an omission, a defect, that you might want to report
    to the committee...

    Victor Bazarov, Mar 15, 2014
    1. Advertisements

  3. Any compiler must know about abstract classes anyway. Simply because it
    is an error to create instances of abstract classes.

    The more interesting point is what the standard says about this. Maybe
    just gcc is broken.

    Marcel Müller, Mar 15, 2014
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.