I have a class which I want to be in a namespace. I have been doing it like
namespace ns {
class A;
}
class ns::A {
...
public:
A();
};
and I define the constructor in a separate file like
ns::A::A() {
...
}
My question is about the correct way of defining the constructor. Is that the correct way, or should I add the namespace to the declaration?
namespace ns {
class A;
}
class ns::A {
...
public:
ns::A();
};
And if that's the case, how is the constructor defined in a separate file?
how is the constructor defined in a separate file?
You can do it as shown below:
header.h
#ifndef HEADER_H
#define HEADER_H
namespace NS
{
//class definition
class A
{
public:
//declaration for default constructor
A();
//declaration for member function
void printAge();
private:
int age;
};
}
#endif
source.cpp
#include"header.h"
#include <iostream>
namespace NS
{
//define default constructor
A::A(): age(0)
{
std::cout<<"default consttuctor used"<<std::endl;
}
//define member function printAge
void A::printAge()
{
std::cout<<age<<std::endl;
}
}
main.cpp
#include <iostream>
#include"header.h"
int main()
{
NS::A obj; //this uses default constructor of class A inside namespace NS
obj.printAge();
return 0;
}
Also don't forget to use header guards inside the header file to avoid cyclic dependency(if any).
The output of the program can be seen here
Some of the changes that i made include:
Added include guard in header file header.h.
Added declarations for the default constructor and a member function called printAge inside class A inside the header file.
Defined the default constructor and the member function printAge inside source.cpp.
Used constructor initializer list in the default constructor of class A inside source.cpp.
Method 2
Here we use the scope resolution operator :: to be in the scope of the namespace NS and then define the member functions as shown below:
source.cpp
#include"header.h"
#include <iostream>
//define default constructor
NS::A::A(): age(0)
{
std::cout<<"default consttuctor used"<<std::endl;
}
//define member function printAge
void NS::A::printAge()
{
std::cout<<age<<std::endl;
}
The output of method 2 can be seen here
There are a few different ways to define a constructor (or a method) for a class which is inside a namespace.
Put the definition inside a namespace
namespace ns
{
A::A()
{
...
}
...
}
Use a qualified name for the class
ns::A::A()
{
...
}
My favorite one - "import" the namespace, then forget about its existence in current source file.
using namespace ns;
...
A::A()
{
...
}
Different style may be appropriate in different situations. If your class is big, 1 or 3 may be best. If you have many small classes, 2 may be best.
Related
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.
I am new at C++ language and I am trying to understand why the next thing is happening:
I have a header file header.h
namespace myNamespace{
class myClass{
public:
myClass();
~myClass();
void myFunction(void);
}
void myVoid();
}
The definitions are in header.cpp
using namespace myNamespace;
void myClass::myFunction(void){
//DO anything
}
void myVoid(){
//Do anything
}
And in the main.cpp I have the follow:
#include "header.h"
main(){
myVoid();
myNamespace::myVoid();
}
Why If I try to call myFunction of the class myClass from the main I have a successful compile, and if I try to call the function as in the main file I have an undefined reference error? I can fix it if in the header.h moves myVoid out of the namespace.
Why is this happening? I am trying to figure out how this works.
Thanks in advice,
If you don't specify definition of myVoid (I mean just declaring it like you did), then the compiler can never be sure if you are implementing the function which is declared in namespace or just defining a new one.
On the other hand, if you are defining myClass::myFunction, it has to be the method that is declared in the defined class.
To make it clear, investigate the following code and take a look here (very similar question)
namespace Test {
int myVoid(void); // declaration
class yourClas; // declaration
class myClass{ // definition
public:
myClass();
~myClass();
void myFunction(void); // declaration which belongs to defined class
}
}
void myVoid() {
// definition, but compiler can't be sure this is the function
// that you mention in the namespace or a new function declaration.
}
void myClass::myFunction(void){
// absolutely definition for the method of the corresponding class
}
Not sure if this is possible, but I have two classes of the same name in different levels of a nested namespace and I'd like to make the more shallow class a friend of the deeper class. Example:
In File1.h:
namespace A
{
class Foo
{
//stuff
};
}
In File2.h:
namespace A
{
namespace B
{
class Foo
{
friend class A::Foo; //Visual Studio says "Error: 'Foo' is not a member of 'A'"
};
}
}
Is this possible? If so, what is the proper syntax?
This code compiles ok when placed in one file (except that a ; is necessary after A::B::Foo class): IdeOne example.
So, the issue is in the code not included in the question text. Probably #include "File1.h" was forgotten in File2.h.
If you want to avoid including large header files into others, you need to at least forward declare your classes before using them:
namespace A
{
class Foo;
namespace B
{
class Foo
{
friend class A::Foo;
}
}
}
Is it possible to use a class defined in an anonymous namespace as a parameter in a private member function? I haven’t found a way to forward declare AnonymousHelperClass in the header.
// C.h
class C
{
// ...
private:
void Boing(AnonymousHelperClass &helper);
};
.
// C.cpp
namespace
{
class AnonymousHelperClass
{
// . . .
};
}
C::Boing(AnonymousHelperClass &helper)
{
// ...
}
No, because there is no way to name the type in the header file.
However, you could turn the private member function into a template:
// C.h
class C
{
public:
void Foo();
private:
template <typename TAnonymousHelper>
void Boing(TAnonymousHelper&);
};
Then define it in the source file and use it with the AnonymousHelperClass:
// C.cpp
#include "C.h"
namespace
{
class AnonymousHelperClass { };
}
template <typename TAnonymousHelper>
void C::Boing(TAnonymousHelper& x) { }
void C::Foo()
{
AnonymousHelperClass x;
Boing(x);
}
Though really, it's probably easier just to rework your logic such that the private member function can be a namespace-scope function in the .cpp file.
No, because unnamed namespaces (that's what they're actually called) are defined like this in the C++ standard:
7.3.1.1 Unnamed namespaces [namespace.unnamed]
1. An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
where all occurrences of unique in a translation unit are replaced by
the same identifier and this identifier differs from all other
identifiers in the entire program.
So with your class it's equivalent to:
namespace SomeUniqueNameGeneratedByTheCompiler {}
using namespace SomeUniqueNameGeneratedByTheCompiler;
namespace SomeUniqueNameGeneratedByTheCompiler
{
class AnonymousHelperClass
{
// . . .
};
}
So the full qualification of the AnonymousHelperClass class is ::SomeUniqueNameGeneratedByTheCompiler::AnonymousHelperClass, not ::AnonymousHelperClass. So even if you did this:
class AnonymousHelperClass; // Forward declaration
class C
{
// ...
private:
void Boing(AnonymousHelperClass &helper);
};
That forward declaration refers to a different AnonymousHelperClass. You could put the forward declaration in the SomeUniqueNameGeneratedByTheCompiler namespace, but since only the compiler knows this name, it can't be done.
I am trying to use the pimpl pattern and define the implementation class in an anonymous namespace. Is this possible in C++? My failed attempt is described below.
Is it possible to fix this without moving the implementation into a namespace with a name (or the global one)?
class MyCalculatorImplementation;
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
MyCalculatorImplementation* pimpl;
};
namespace // If i omit the namespace, everything is OK
{
class MyCalculatorImplementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
}
// error C2872: 'MyCalculatorImplementation' : ambiguous symbol
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
int MyCalculator::CalculateStuff(int x)
{
return pimpl->Calculate(x);
}
No, the type must be at least declared before the pointer type can be used, and putting anonymous namespace in the header won't really work. But why would you want to do that, anyway? If you really really want to hide the implementation class, make it a private inner class, i.e.
// .hpp
struct Foo {
Foo();
// ...
private:
struct FooImpl;
boost::scoped_ptr<FooImpl> pimpl;
};
// .cpp
struct Foo::FooImpl {
FooImpl();
// ...
};
Foo::Foo() : pimpl(new FooImpl) { }
Yes. There is a work around for this. Declare the pointer in the header file as void*, then use a reinterpret cast inside your implementation file.
Note: Whether this is a desirable work-around is another question altogether. As is often said, I will leave that as an exercise for the reader.
See a sample implementation below:
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
void* pimpl;
};
namespace // If i omit the namespace, everything is OK
{
class MyCalculatorImplementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
}
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
MyCalaculator::~MyCalaculator()
{
// don't forget to cast back for destruction!
delete reinterpret_cast<MyCalculatorImplementation*>(pimpl);
}
int MyCalculator::CalculateStuff(int x)
{
return reinterpret_cast<MyCalculatorImplementation*>(pimpl)->Calculate(x);
}
No, you can't do that. You have to forward-declare the Pimpl class:
class MyCalculatorImplementation;
and that declares the class. If you then put the definition into the unnamed namespace, you are creating another class (anonymous namespace)::MyCalculatorImplementation, which has nothing to do with ::MyCalculatorImplementation.
If this was any other namespace NS, you could amend the forward-declaration to include the namespace:
namespace NS {
class MyCalculatorImplementation;
}
but the unnamed namespace, being as magic as it is, will resolve to something else when that header is included into other translation units (you'd be declaring a new class whenever you include that header into another translation unit).
But use of the anonymous namespace is not needed here: the class declaration may be public, but the definition, being in the implementation file, is only visible to code in the implementation file.
If you actually want a forward declared class name in your header file and the implementation in an anonymous namespace in the module file, then make the declared class an interface:
// header
class MyCalculatorInterface;
class MyCalculator{
...
MyCalculatorInterface* pimpl;
};
//module
class MyCalculatorInterface{
public:
virtual int Calculate(int) = 0;
};
int MyCalculator::CalculateStuff(int x)
{
return pimpl->Calculate(x);
}
namespace {
class MyCalculatorImplementation: public MyCalculatorInterface {
...
};
}
// Only the ctor needs to know about MyCalculatorImplementation
// in order to make a new one.
MyCalculator::MyCalculator(): pimpl(new MyCalculatorImplementation)
{
}
markshiz and quamrana provided the inspiration for the solution below.
class Implementation, is intended to be declared in a global header file and serves as a void* for any pimpl application in your code base. It is not in an anonymous/unnamed namespace, but since it only has a destructor the namespace pollution remains acceptably limited.
class MyCalculatorImplementation derives from class Implementation. Because pimpl is declared as std::unique_ptr<Implementation> there is no need to mention MyCalculatorImplementation in any header file. So now MyCalculatorImplementation can be implemented in an anonymous/unnamed namespace.
The gain is that all member definitions in MyCalculatorImplementation are in the anonymous/unnamed namespace. The price you have to pay, is that you must convert Implementation to MyCalculatorImplementation. For that purpose a conversion function toImpl() is provided.
I was doubting whether to use a dynamic_cast or a static_cast for the conversion. I guess the dynamic_cast is the typical prescribed solution; but static_cast will work here as well and is possibly a little more performant.
#include <memory>
class Implementation
{
public:
virtual ~Implementation() = 0;
};
inline Implementation::~Implementation() = default;
class MyCalculator
{
public:
MyCalculator();
int CalculateStuff(int);
private:
std::unique_ptr<Implementation> pimpl;
};
namespace // Anonymous
{
class MyCalculatorImplementation
: public Implementation
{
public:
int Calculate(int input)
{
// Insert some complicated calculation here
}
private:
int state[100];
};
MyCalculatorImplementation& toImpl(Implementation& impl)
{
return dynamic_cast<MyCalculatorImplementation&>(impl);
}
}
// no error C2872 anymore
MyCalculator::MyCalculator() : pimpl(std::make_unique<MyCalculatorImplementation>() )
{
}
int MyCalculator::CalculateStuff(int x)
{
return toImpl(*pimpl).Calculate(x);
}