Search code examples
c++visual-c++compiler-errorsheader-filesredefinition

C++ 'class' type redefinition error


I'm learning Visual C++ and building the "Sketcher" example program from Ivor Horton's Visual book, and I was able to generate the toolbars, menu icons, prompts, and a rectangle drawn with a few hard-coded points. After adding some mouse handlers and references to a few other header files, I receive this error: error C2011: 'CElement' : 'class' type redefinition.

Because of this "redefinition", there are 40+ errors thrown in the other shape classes that were previously based on CElement can't seem to find that class at compile time although the Visual Studio's intellisense seems to detect it just fine. I don't think I'm missing anything since everything compiled properly before my last few changes, but I've exhausted my undo/redo history and can't seem to find a root cause.

I've looked at some of the other answers related to this error message, but I'm still stuck on pinpointing exactly where my class is being defined a second time.

My Element.h file contains the following code:

#include <algorithm>
#include "stdafx.h"
class CElement : public CObject
{
protected:
    CPoint m_StartPoint; // Element position
    int m_PenWidth; // Pen width
    COLORREF m_Color; // Color of an element
    CRect m_EnclosingRect; // Rectangle enclosing an element

    // Create a pen
    void CreatePen(CPen& aPen);
public:
    virtual ~CElement();
    virtual void Draw(CDC* pDC) {} // Virtual draw operation
    // Get the element enclosing rectangle
    const CRect& GetEnclosingRect() const { return m_EnclosingRect; }
protected:
    // Constructors protected so they cannot be called outside the class
    CElement();
    CElement(const CPoint& start, COLORREF color, int penWidth = 1);
};

My Element.cpp file contains the following code:

#include "stdafx.h"
#include "Element.h"


CElement::CElement()
{
}

void CElement::CreatePen(CPen& aPen)
{
    if (!aPen.CreatePen(PS_SOLID, m_PenWidth, m_Color))
    {
        // Pen creation failed
        AfxMessageBox(_T("Pen creation failed."), MB_OK);
        AfxAbort();
    }
}

CElement::~CElement()
{
}

Solution

  • Suggestion: use an include guard, in ALL of your header files:

    Element.h:

    #ifndef ELEMENT_H
    #define ELEMENT_H
    
    #include <algorithm>
    #include "stdafx.h"
    
    class CElement : public CObject
    {
    protected:
        CPoint m_StartPoint; // Element position
        ...
    protected:
        // Constructors protected so they cannot be called outside the class
        CElement();
        CElement(const CPoint& start, COLORREF color, int penWidth = 1);
    };
    
    #endif