roguemacro
roguemacro

Reputation: 319

C++ - 'class' type redefinition

I made a smaller reproducible version of the code that gave me these errosr: 'MyNamespace::MySecondClass': 'class' type redefinition, 'print': is not a member of 'MyNamespace::MySecondClass'. Is there any way of working around this problem?

// MyClass.h

#pragma once

namespace MyNamespace {

    class MySecondClass {};

}

// MyClass.cpp

#include "MyClass.h"
#include <iostream>

using namespace std;

class MyNamespace::MySecondClass
{
public:
    void print(const char* msg)
    {
        cout << msg << endl;
    }
};

Upvotes: 1

Views: 1198

Answers (1)

Christophe
Christophe

Reputation: 73436

The problem is that in MyClass.h you define a class MySecondClass as an empty class. When you the define your class in MyClass.cpp you give a different definition, which contains some new members. This infringes the One Definition Rule (ODR).

Solution 1

remove {} in the header. This will tell the compiler that you declare that such a class exists but that it will be defined later. Your code would compile. Unfortunately if you’d include the header in other cpp, these could make only a very very limited use of MySecondClass.

Solution 2

define in the header the class with all its members (but without providing the implementation of the member functions:the signature is sufficient). This would allow the class to be used in whichever cpp that would include it:

// MyClass.h
#pragma once
namespace MyNamespace {
    class MySecondClass {
    public:
        void print(const char* msg);
    };
}

You’d then define the members of the class in its cpp in the appropriate namespace:

// MyClass.cpp
#include <iostream>
#include "MyClass.h"

using namespace std;

namespace MyNamespace {
    // member functions
    void MySecondClass::print(const char* msg)
    {
        cout << msg << endl;
    }
}

Remark: the include sequence in the cpp should first include the standard library headers, then only your own headers. It makes no difference in your simple example, but better get used the good practices immediately.

Upvotes: 3

Related Questions