My problem statement is as below. There is a concept of “domain” which consists of many “subdomains”. Now, those subdomains are domains in their own right. Following is the basic method I can do the things. I can probably use an auto_ptr or something, but lets leave it for now.
class Domain
{
private:
Domain* subdomains;
}
However, I was able to compile and run the following program which I think does the same thing and gives me what I want.
#include <iostream>
#include <vector>
#include <string>
class Domain
{
private:
std::string name_;
public:
std::vector<Domain> subdomains;
Domain(std::string name) : name_(name) {};
std::string name() {return name_;}
void addSubDomain(std::string subDomainName);
};
void Domain::addSubDomain(std::string subDomainName)
{
subdomain.push_back(Domain(subDomainName));
}
int main()
{
std::cout<<"Hello, World"<<std::endl;
Domain domain("wow");
domain.addSubDomain("wow-child");
std::cout<<"Domain name is "<<domain.name()<<std::endl;
std::cout<<"Subdomain name is "<<domain.subdomain[0].name()<<std::endl;
return 0;
}
The output which I get on running this is
$./main
Hello, World
Domain name is wow
Subdomain name is wow-child
My question is whether there are any pitfalls that I may have missed while implementing the following thing? Right now, there is nothing I can see. If there are no pitfalls, then this is the a really good solution to my problems.
EDIT
In case this is not a solution, then is there another solution that I can use which does not involve the management of raw pointers?
This is undefined behavior because at the point you define the member, the class is not yet completely defined. At that point,
std::vector<Domain>needs to be instantiated though, from the templatestd::vector<T>to a classstd::vector<Domain>(to determine its size, among others). When that instantiation happens, the Standard requires the class to be completely defined.