Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with C++ abstract class (I can do it in Java, but not in C++!)

First of all, I searched this problem and found a lot of similiar questions, but I couldn't find an answer that fixed my problem. I am very sorry if that is just me being dumb.

What I am trying to do is make the constructor of an abstract class call a function that is pure virtual. In Java, this works, because the subclass provides the implementation of the abstract method that is called. However, in C++, I get this linker error:

test.o:test.cpp:(.text$_ZN15MyAbstractClassC2Ev[MyAbstractClass::MyAbstractClass
()]+0x16): undefined reference to `MyAbstractClass::initialize()'
collect2: ld returned 1 exit status

Here is my code:

#include <iostream>

class MyAbstractClass {
protected:
    virtual void initialize() = 0;

public:
    MyAbstractClass() {
        initialize();
    }
};

class MyClass : public MyAbstractClass {
private:
    void initialize() {
        std::cout << "yey!" << std::endl;
    }
};

int main() {
    MyClass *my = new MyClass();
    return 0;
}

As a further explanation of what I am trying to do, here is code in Java that achieves my goal:

public abstract class MyAbstractClass {

    public MyAbstractClass() {
        initialize();
    }

    protected abstract void initialize();
}

public class MyClass extends MyAbstractClass {

    protected void initialize() {
        System.out.println("Yey!");
    }

    public static void main(String[] args) {
        MyClass myClass = new MyClass();
    }
}

This code prints "Yey!". Any help much appreciated!

like image 521
Vilius Kazakauskas Avatar asked Feb 27 '12 23:02

Vilius Kazakauskas


4 Answers

MyAbstractClass() {
    initialize();
}

That will not perform a virtual dispatch to MyClass::initialize(), because at this stage of the object's construction its MyClass parts haven't been created yet. Thus you really are invoking MyAbstractClass::initialize() and, as such, it must be defined. (Yes, pure virtual member functions can be defined.)

Try to avoid invoking virtual member functions from constructors, because this sort of stuff will happen and catch you out. It rarely makes sense to do it.

Also, try to avoid initialize() functions; you already have constructors to play with.


Update

Actually, though you may take the above as read for any other virtual member function, invoking a pure virtual member function from the constructor yields Undefined Behaviour. So don't even try!

like image 155
Lightness Races in Orbit Avatar answered Nov 15 '22 03:11

Lightness Races in Orbit


In C++, you can't call a pure virtual function from a constructor or destructor (even if it has a definition). If you call a non-pure one, then it will be dispatched as if the object's type were the class under construction, so you'll never be able to call a function defined in a derived class.

In this case, you don't need to; the derived class's constructor will be called after the base class's, so you get the desired result from:

#include <iostream>

class MyAbstractClass {
public:
    MyAbstractClass() {
        // don't do anything special to initialise the derived class
    }
};

class MyClass : public MyAbstractClass {
public:
    MyClass() {
        std::cout << "yey!" << std::endl;
    }
};

int main() {
    MyClass my;
    return 0;
}

Note that I also changed my to an automatic variable; you should get in the habit of using them whenever you don't need dynamic allocation, and learn how to use RAII to manage dynamic resources when you really do need them.

like image 37
Mike Seymour Avatar answered Nov 15 '22 03:11

Mike Seymour


Let me quote Scott Meyers here (see Never Call Virtual Functions during Construction or Destruction):

Item 9: Never call virtual functions during construction or destruction.

I'll begin with the recap: you shouldn't call virtual functions during construction or destruction, because the calls won't do what you think, and if they did, you'd still be unhappy. If you're a recovering Java or C# programmer, pay close attention to this Item, because this is a place where those languages zig, while C++ zags.

The issue: during object construction the virtual function table might not yet be ready. Just imagine that your class is eg. fourth in line of inheritance. Constructors are called in inheritance order, so while calling this pure virtual (or even if it was non-pure) you would like the base class to call initialize for an object that is not yet complete!

like image 25
Marcin Gil Avatar answered Nov 15 '22 03:11

Marcin Gil


The C++ side has been handled in other answers, but I want to add a remark on the Java side of it. Calling a virtual function from a constructor is a problem in all cases, not just in C++. Basically what the code is trying to do is execute a method on an object that has not yet been created and that is an error.

The two solutions implemented in the different languages differ in trying to make some sense of what your code is trying to do. In C++ the decision is that during construction of a base object, and until construction of the derived object starts, the actual type of the object is base, which means that there won't be dynamic dispatch. That is, the type of the object at any time is that of the constructor being executed[*]. While this is surprising to some (you among others), it provides a sensible solution to the problem.

[*] Conversely the destructor. The type also changes as the most derived constructors complete.

The alternative in Java is that the object is of the final type from the beginning, even before construction has completed. In Java, as you demonstrated, the call will be dispatched to the final overrider (I am using C++ slang here: to the last implementation of the virtual function in the execution chain), and that can cause unwanted behavior. Consider for example this implementation of initialize():

public class MyClass extends MyAbstractClass {
   final int k1 = 1;
   final int k2;
   MyClass() {
      k2 = 2;
   }
   void initialize() {
      System.out.println( "Constant 1 is " + k1 + " and constant 2 is " + k2 );
   }
}

What is the output of the previous program? (Answer at the bottom)

More than just a toy example, consider that MyClass provides some invariants that are set at construction time and hold for the whole lifetime of the object. Maybe it holds a reference to a logger on which data can be dumped. By looking at the class, you can see that the logger is set in the constructor and assume that it cannot be reset anywhere in the code:

public class MyClass extends MyAbstractClass {
   Logger logger;
   MyClass() {
      logger = new Logger( System.out );
   }
   void initialize() {
      logger.debug( "Starting initialization" );
   }
}

You probably see now where this is going. By looking at the implementation of MyClass there does not seem to be anything wrong at all. logger is set in the constructor, so it can be used in all methods of the class. Now the problem is that if MyAbstractClass calls on a virtual function that gets dispatched then the application will crash with a NullPointerException.

By now I hope that you understand and value the C++ decision of not performing dynamic dispatch and thus avoid executing functions on objects that have not yet been fully initialized (or conversely have already been destroyed, if the virtual call is in the destructor).

(Answer: this might depend on the compiler/JVM, but when I tried this long long time ago, the line printed Constant 1 is 1 and constant 2 is 0. If you are happy with that, fine by me, but I found that to be surprising... The reason for the 1/0 in that compiler is that the process of initialization first sets the values that are in the variable definition, and then calls the constructors. This means that the first step of construction would set k1 before calling MyAbstractBase constructor, that would call initialize() before MyBase constructor has run and set the value of the second constant).

like image 38
David Rodríguez - dribeas Avatar answered Nov 15 '22 03:11

David Rodríguez - dribeas