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;
}
};
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.
Related
Firstly, I am giving the codes. Then I am explaining the problem I am facing.
main.cpp
#include <iostream>
#include "acc.h"
using namespace std;
class mem;
int main()
{
show();
return 0;
}
acc.h
#ifndef ACC_H
#define ACC_H
#include "acc.cpp"
void show();
class mem{
int a;
public:
void showa();
void seta(int A);
};
#endif
acc.cpp
#include <iostream>
using namespace std;
void mem::showa(){cout<<a<<endl;}
void mem::seta(int A){a = A;}
void show()
{
mem m;
m.seta(22);
string ss;
cin>>ss;
cout<<"MY name is "<<ss<<" ";
m.showa();
}
"mem" class I declared in "acc.h" file already and added that "acc.h" into acc.cpp file also. But when I am calling that class from a function. It can't response. Showing "a" and "mem" not declared. How can I perfectly link that class definition and member functions of that class so that calling member functions of that class from another function can't create any problem?
If you remove the #include "acc.cpp" from the acc.h file it should compile without any errors. I tried and it compiles for me. I am using Visual Studio 2010 for the same.
Other than this, few more comments:
You can use #pragma once in you header file instead of #ifndef/#define macros. The former is more cleaner.
You dont need to forward declare class mem before main() as you are already including acc.h.
the show() can be moved to where main() is defined making the acc.h/acc.cppfiles dedicated for the mem class.
A header file should always be named after the class it is holding i.e. mem.h/mem.cpp in your case. This informs which file contains which class even without opening the file.
Below are by 4 classes, I'm learning about basic c++ syntax and boy is it much harder and less forgiving than other languages I have used. I have a main class, base class "BaseArray" and two sub classes "OrderedArray" and "UnorderedArray".
Main.cpp
#include <iostream>
#include "OrderedArray.cpp"
#include "UnorderedArray.cpp"
using namespace std;
int main() {
system("PAUSE");
return 0;
}
BaseArray.cpp
#include <iostream>
using namespace std;
class BaseArray {
public:
BaseArray::BaseArray() {
}
};
OrderedArray.cpp
#include <iostream>
#include "BaseArray.cpp"
using namespace std;
class OrderedArray : public BaseArray {
OrderedArray::OrderedArray() {
}
};
UnorderedArray.cpp
#include <iostream>
#include "BaseArray.cpp"
using namespace std;
class UnorderedArray : public BaseArray {
UnorderedArray::UnorderedArray() {
}
};
The errors I receive are as followed, from scouting other threads online. I think it might have to do with duplicate calling of classes. To be honest, I have no clue. If someone could point me in the right direction that would be nice, thanks in advance!
error C2011: 'BaseArray':'class' type redefinition
error C2504: 'BaseArray':base class undefined
To fix this error I can remove one of the includes at the top of main.cpp, but I need those to create objects and call functions from the subclasses later on.
You should put your base array in a header:
BaseArray.h
#ifndef BASEARRAY_H_GUARD // include guard
#define BASEARRAY_H_GUARD // include guard
// no using namespace !!
// only includes needed for what's in the header
class BaseArray {
public:
BaseArray();
};
#endif // include guard
And then leave in the cpp only the implementation part of your class:
BaseArray.cpp
#include <iostream>
#include "BaseArray.h"
using namespace std;
BaseArray::BaseArray() { // no need class enclosing: the BaseArray:: prefix is sufficient
}
The you can apply the same principle to the derived classes:
OrderedArray.h
#ifndef BASEARRAY_H_GUARD // include guard
#define BASEARRAY_H_GUARD // include guard
#include "BaseArray.h" // include only those that you need but all those that you need
class OrderedArray : public BaseArray { // requires BaseArray
OrderedArray();
};
#endif
OrderedArray.cpp
#include <iostream> // include headers that are needed for class implementation
#include "OrderedArray.h" // this should be self contained and provide
// evertyhing that is needed for the class itself
using namespace std;
OrderedArray::OrderedArray() {
}
You then have to do the same for UnorderedArray and finally, you have to adapt your main.cpp to include .h instead of .cpp. And you're done.
A final remark: your cpp source code files are now ready for separate compilation. This means that you can no longer compile only main.cpp, hoping that it includes all the code: you have now to compile the 4 cpp files and link them together.
Following my previous question. I've settled on using using directives to alias types inside my classes to avoid importing other stuff and polluting other headers that use these offending headers.
namespace MyLibrary {
namespace MyModule1 {
class MyClass1 {
public:
float X;
float Y;
MyClass1(float x, float y): X(x), Y(y) {}
};
} // namespace MyModule1
namespace MyModule2 {
class MyClass2 {
private:
// as suggested in linked question
using MyCustomType1 = MyLibrary::MyModule1::MyClass1;
public:
void DoSomething(MyCustomType1 parameter) {
std::cout << parameter.X << std::endl;
std::cout << parameter.Y << std::endl;
}
};
} // namespace MyModule2
} // namespace MyLibrary
int main(int argc, char* argv[])
{
MyLibrary::MyModule1::MyClass1 some_parameter(1.0f, 2.0f);
MyLibrary::MyModule2::MyClass2 some_var;
// Can't do this
// MyLibrary::MyModule2::MyClass2::MyCustomType1 some_other_var;
// But I can do this
some_var.DoSomething(some_parameter);
return 0;
}
How will the users outside of the MyLibrary namespace know what is MyCustomType1 if it is aliased inside a class (privately)?
Is my usage here of using legal, or is this a dirty hack I'm accidentally doing?
They will know for the simple reason you have to #include the declarations of both classes.
Having read this, and the previous question, I think the missing concept here is the concept of forward declarations.
Consider the following header file, let's called this file mymodule1_fwd.H:
namespace MyLibrary {
namespace MyModule1 {
class MyClass1;
} // namespace MyModule1
}
That's it. This is sufficient for you to declare MyClass2:
#include "mymodule1_fwd.H"
namespace MyModule2 {
class MyClass2 {
private:
// as suggested in linked question
using MyCustomType1 = MyLibrary::MyModule1::MyClass1;
public:
void DoSomething(MyCustomType1 parameter);
};
} // namespace MyModule2
Note that including this header file only will not really automatically get the entire MyModule class declaration. Also note the following:
You can't define the contents of the inline DoSomething() class method, because it actually uses the aliased type. This has the following consequences:
You have to define the DoSomething() method somewhere, in some way, probably inside the .C implementation translation module.
Similarly, you have to have declare the actual MyClass1 class from the mymodule1_fwd.H header file. I am using my own personal naming convention here, "filename_fwd.H" for forward declarations, the forward declaration header file; and "filename.H" for the actual class implementation, the implementation header file.
Callers of the DoSomething() method will have to explicitly #include the actual class declaration header file for MyClass, since they have to pass it as a parameter.
You can't really avoid the fact that the callers have to know the class that they're actually using to pass parameters. But only the callers of the DoSomething() method will need that. Something that uses other parts of the MyClass2, and don't invoke DoSomething(), don't need to know anything about MyClass1, and the actual class declaration won't be visible to them unless they explicitly #include the class implementation header file.
Now, if you still need DoSomething() to be inlined, for performance reasons, there are a couple of tricks that can be used, with preprocessor directives, that if someone #includes all the necessary header files, they'll get the inlined declaration of the DoSomething() method.
But that'll have to be another question.
I'm using the CRTP pattern to create an interface, which other classes will derive from.
In the interface I forward declare a structure (important because I don't want to drag other stuff in the interface), but I include its definition in the cpp file which defines the interface.
Interface.h
#ifndef INTERFACE_H_INCLUDED
#define INTERFACE_H_INCLUDED
// forward declaration
class ForwardDecl;
template <class Derived>
class Interface
{
public:
ForwardDecl interfaceMethod();
};
#endif // INTERFACE_H_INCLUDED
ForwardDecl.h
#ifndef FORWARDDECL_H_INCLUDED
#define FORWARDDECL_H_INCLUDED
struct ForwardDecl
{
ForwardDecl(int i):internal(i)
{}
int internal;
};
#endif // FORWARDDECL_H_INCLUDED
Interface.cpp
#include "Interface.h"
#include "ForwardDecl.h"
template<class Derived>
ForwardDecl Interface<Derived>::interfaceMethod()
{
return static_cast<Derived *>(this)->implementation_func();
}
And this is the implementation which implements the interface
Implementation.h
#ifndef IMPLEMENTATION_H_INCLUDED
#define IMPLEMENTATION_H_INCLUDED
#include "Interface.h"
class ForwardDecl;
class Implementation: public Interface<Implementation>
{
friend class Interface<Implementation>;
private:
ForwardDecl implementation_func();
};
#endif // IMPLEMENTATION_H_INCLUDED
Implementation.cpp
#include "Implementation.h"
#include "ForwardDecl.h"
#include <iostream>
struct ForwardDecl Implementation::implementation_func()
{
ForwardDecl fd(42);
std::cout << fd.internal << std::endl;
return fd;
}
And the main file
#include <iostream>
#include "Implementation.h"
#include "ForwardDecl.h"
using namespace std;
int main()
{
Implementation impl;
ForwardDecl fd = impl.interfaceMethod();
cout << fd.internal << endl;
return 0;
}
I get linking errors on both VS and GCC.
Any workaround? Thank you.
There is a flaw in your very approach: You have a public function returning a ForwardDecl instance, so every client wanting to use this function also must include the according definition of that type, which implies you can make that type public from the beginning. This includes making the function definition inline, which will fix your linker problems.
However, if you really want to hide the content of that structure and you are sure clients don't need it directly, you can declare it and then pass around references to such a structure (or pointers, but raw pointers are evil albeit not in the same league of evil as #macros). In that case, I would still make the function definition inline.
If you really, really want to not make the function inline, you can also explicitly instantiate the function template for the types that you need. You would add at the end of the template's .cpp file something like template class Interface<int>; (I don't remember the exact syntax so take that with a few flakes of fleur de sel, check out the C++ FAQ at parashift.com for more info). This makes the template a little less universal though, as it requires adjustments for any type that you want to use it with, but it can be an approach in some corner cases.
The definitions of function templates and member functions of class templates need to be visible in all translation units that instantiate those templates. That is, you shouldn't put template definitions in a .cpp file, which means you need to move the contents of Interface.cpp up into Interface.h.
I'm starting to learn C++ (coming from Java), so bear with me.
I can't seem to get my method declaration to accept a class I've made.
'Context' has not been declared
I think I'm not understanding a fundamental concept, but I don't know what.
Expression.h
#include "Context.h"
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h
#include <stack>
#include <vector>
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
You have to forward declare Expression in Context or vice versa (or both), otherwise you have a cyclic dependency. For example,
Expression.h:
class Context; // no include, we only have Context*.
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
};
Context.h:
#include <stack>
#include <vector>
class Expression; // No include, we only have Expression*
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
};
You can perform the forward declarations because the full definition of the classes isn't needed, since you are only referring to pointers to the other class in each case. It is likely that you will need the includes in the implementation files (that is, #include "Context.h" in Expression.cpp and #include Expression.h in Context.cpp).
Finally, remember to put include guards in your header files.
In C++, class definitions always have to end with a semi-colon ;
so example:
class foo {};
Java and C# doesn't require that, so I can see your confusion.
Also it looks like both your header files include each other. Thus it's kind of like a snake eating it's tail: Where does it start? Thus in your Expression.h you can replace the 'include' with a forward declaration instead:
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
And last but not least, you should put a compiler guard to prevent the header from getting included more than once into a .cpp file. You can put a #pragma once in the top of the header file. That is useful if you are using visual studio and the microsoft compiler. I don't know if GCC supports it or not. Or you can wrap your header file like this:
#ifndef EXPRESSION_H_
#define EXPRESSION_H_
class Context;
class Expression {
public:
void interpret(Context *); // This line has the error
Expression();
virtual ~Expression();
}
#endif
you might need to forward declare the classes Context and Expression in the header files before the #include
e.g.
#include <stack>
#include <vector>
// forward declaration
class Context;
class Expression;
#include "Expression.h"
class Context {
private:
std::stack<Expression*,std::vector<Expression*> > theStack;
public:
Context();
virtual ~Context();
}