I have a C++/WinRT base class that I need to subclass. My problem is that I don't manage to call the base class's protected constructor from the subclass.
That base class is defined in MIDL as follows:
namespace My.Custom.WindowsRuntimeComponent
{
unsealed runtimeclass BaseClass : Windows.UI.Xaml.Controls.SwapChainPanel
{
}
}
From it, the following header and implementation is created:
#pragma once
#include <DirectXMath.h>
#include "BaseClass.g.h"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
struct BaseClass : BaseClassT<BaseClass>
{
protected:
BaseClass();
::DirectX::XMFLOAT3 ProtectedMethod();
};
}
#include "pch.h"
#include "BaseClass.h"
#include "BaseClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
BaseClass::BaseClass()
{
// Important stuff happening here
}
::DirectX::XMFLOAT3 BaseClass::ProtectedMethod()
{
return ::DirectX::XMFLOAT3();
}
}
The subclass's MIDL, header and implementation are defined as follows:
import "BaseClass.idl";
namespace My.Custom.WindowsRuntimeComponent
{
runtimeclass SubClass : BaseClass
{
SubClass();
void UseProtectedMethod();
}
}
#pragma once
#include "BaseClass.h"
#include "SubClass.g.h"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
struct SubClass : SubClassT<SubClass, My::Custom::WindowsRuntimeComponent::implementation::BaseClass>
{
SubClass();
void UseProtectedMethod();
};
}
namespace winrt::My::Custom::WindowsRuntimeComponent::factory_implementation
{
struct SubClass : SubClassT<SubClass, implementation::SubClass>
{
};
}
#include "pch.h"
#include "SubClass.h"
#include "SubClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
SubClass::SubClass()
{
}
void SubClass::UseProtectedMethod()
{
::DirectX::XMFLOAT3 value = ProtectedMethod();
}
}
The above example compiles. However, if I attempt to call the protected base class constructor from the initializer list of the subclass as shown below I receive a compiler error.
#include "pch.h"
#include "SubClass.h"
#include "SubClass.g.cpp"
namespace winrt::My::Custom::WindowsRuntimeComponent::implementation
{
SubClass::SubClass() : BaseClass() // This line does not compile
{
}
void SubClass::UseProtectedMethod()
{
::DirectX::XMFLOAT3 value = ProtectedMethod();
}
}
The compiler error is as follows:
error C2614: 'winrt::My::Custom::WindowsRuntimeComponent::implementation::SubClass': illegal member initialization: 'BaseClass' is not a base or member
Both in the MIDL and the header of SubClass
I specify that it inherits from BaseClass
so it is unclear to me why the compiler emits that error.
I could work around that problem, I guess, but I'm curious about what exactly is going on here. Any hints?
The
SubClass
in thewinrt::...
namespace derives fromSubClassT<...>
, not fromSubClass
.The
SubClass
that is outside thewinrt::
namespace derives from BaseClass, but thats a different one. Your naming is easy to get lost in.