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?
CodePudding user response:
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 classA
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
CodePudding user response:
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.