Calling pure virtual functions in constructor of base class is UB
Obviously it shouldn’t work as definition of foo() is not available in A()1 , the thing is that it’s UB2 .
#include <iostream>
class A {
public:
A() {
std::cout << "A()" << std::endl;
std::cout << this->foo() << std::endl;
}
virtual int foo() = 0;
};
class B : A {
public:
B() {
std::cout << "B()" << std::endl;
std::cout << this->foo() << std::endl;
}
int foo() { return 2; }
};
int main(int __attribute__((unused)) argc,
char __attribute__((unused)) * argv[],
char __attribute__((unused)) * envp[]) {
B aux;
return 0;
}
Compiler throws a warning… and linker throws this error:
[ecomaikgolf@desktop ../testcpp/c3328e227d1cdcfa]$ make run
bear -- g++ -include .utils.h -Wall -Wextra -o a.out main.cpp
main.cpp: En el constructor ‘A::A()’:
main.cpp:13:27: aviso: pure virtual ‘virtual int A::foo()’ called from constructor
13 | std::cout << this->foo() << std::endl;
| ~~~~~~~~~^~
/usr/bin/ld: /tmp/ccYz1yNv.o: en la función `A::A()':
main.cpp:(.text._ZN1AC2Ev[_ZN1AC5Ev]+0x4d): referencia a `A::foo()' sin definir
collect2: error: ld devolvió el estado de salida 1
make: *** [makefile:13: default] Error 1