C++ / D2D1 / Child class: Exception thrown: read access violation. this was nullptr.

Oleksiy F 6 Reputation points
2021-11-17T10:47:50.107+00:00

Hello, I'm trying to create a child class for my main Direct2D class to put all the generic shapes drawing functions in there to keep the main class clean

//parent class definition

class CD2DCore {
protected:
    //COM objects - always release
    ID2D1Factory* gFactory;         //generates D2D resources
    ID2D1HwndRenderTarget* gRT;     //target to draw graphics at
    ID2D1SolidColorBrush* gBrush;   //main brush
public:
    CD2DCore();
    ~CD2DCore();

//......
//rest of CD2DCore code

//child class definition

class CD2DBasic : public CD2DCore {
public:

    //basic shapes framework
    void DrawLine(float x1, float y1, float x2, float y2, float r, float g, float b, float a = 1.0f, float strokeW = 1.0f);

//......
//rest of CD2DBasic code

Then I create entities for both classes like so
CD2DCore* D2DCore; //class for core Direct2D methods
CD2DBasic* D2DBasic; //class for drawing basic Direct2D shapes

But when I'm trying to draw, say, a line through D2DBasic->DrawLine method I get an exception
void CD2DBasic::DrawLine(float x1, float y1, float x2, float y2, float r, float g, float b, float a, float strokeW) {
gBrush->SetColor(D2D1::ColorF(r, g, b, a));
gRT->DrawLine(D2D1::Point2F(x1, y1), D2D1::Point2F(x2, y2), gBrush, strokeW);
}
at the gBrush->SetColor... line stating "read access violation. this was nullptr."

However when I put this same method in CD2DCore - it draws the line without any issues.
I guess it somehow doesn't inherit the parent's pointers to Direct2D stuff?

How do I resolve this?

Windows development Windows API - Win32
Developer technologies C++
{count} votes

1 answer

Sort by: Most helpful
  1. Xiaopo Yang - MSFT 12,731 Reputation points Microsoft External Staff
    2021-11-18T01:18:45.733+00:00

    As far as I see, Nobody calls InitD2D which should be called in CD2DCore constructor.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.