Skip to content

Instantly share code, notes, and snippets.

@bjornblissing
Created June 3, 2016 14:12
Show Gist options
  • Save bjornblissing/1895b168b2e90762ebee065adb3d3c65 to your computer and use it in GitHub Desktop.
Save bjornblissing/1895b168b2e90762ebee065adb3d3c65 to your computer and use it in GitHub Desktop.
Example of how a constructor of abstract class ignores initializer for virtual base class
#include <iostream>
class Foo {
public:
Foo() : _value(0)
{
std::cout << "Constructor: Foo" << std::endl;
}
explicit Foo(int value) : _value(value)
{
std::cout << "Constructor: Foo with argument" << std::endl;
}
virtual void print() = 0;
protected:
int _value;
};
class Bar : virtual public Foo {
public:
Bar() :
Foo(1), // Statement without effect. Will emit warning C4589 in Visual Studio 2015
_value2(10)
{
std::cout << "Constructor: Bar" << std::endl;
}
protected:
int _value2;
};
struct Baz : public Bar {
Baz() :
Foo(2),
Bar()
{
std::cout << "Constructor: Baz" << std::endl;
}
void print() { std::cout << "Print: Foo member variable: " << _value << "\tBar member variable: " << _value2 << std::endl; }
};
int main() {
Baz baz;
baz.print();
return 0;
}
@bjornblissing
Copy link
Author

Will emit the following warning when compiled with Visual Studio 2015:

(21): warning C4589: Constructor of abstract class 'Bar' ignores initializer for virtual base class 'Foo'
(21): note: virtual base classes are only initialized by the most-derived type

@metablaster
Copy link

Thanks for sharing this, I run into this warning, also good read is here:

@bjornblissing
Copy link
Author

In Clang this can be detected by enabling the -Wabstract-vbase-init warning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment