Pls i want to call a constructor within itself but don't know how to.

Recommended Answers

All 4 Replies

I suppose that if you want to call a different version of a constructor inside another of the same class, that you could, although it is HIGHLY ill-advised! So you could do something like this, I suppose (danger Will Robinson!):

class ClassX {
private:
    int knit;
    int perl;
public:
    ClassX();
    ClassX(int);
};

ClassX::ClassX() // default ctor
: knit(1), perl(2)
{
   this->ClassX(6);
}
ClassX::ClassX(int warp)
: knit(warp/2), perl(warp)
{
}

Just remember, that any base classes ClassX is derived from will now be constructed twice as well, possibly resulting in "interesting" side effects, resource depletion, etc.

If you mean that you want to call the constructor from the body of that constructor, recursively. That's possible (with the syntax rubberman showed). However, it is nasty and useless because if you want to create your object through some recursive process, then you can easily put that recursive process in another function (e.g. a private helper function). That solution is much better:

class ClassX {
private:
    int knit;
    int perl;
    void recursingInit(int);
public:
    ClassX();
    ClassX(int);
};

void ClassX::recursingInit(int n) {
  // do something..
  //recurse:
  recursingInit(n-1);
};

ClassX::ClassX() // default ctor
: knit(1), perl(2)
{
   this->recursingInit(6);
}

ClassX::ClassX(int warp)
: knit(warp/2), perl(warp)
{
   this->recursingInit(warp);
}

However, if what you are trying to do is like rubberman described, that is, to call one constructor from another, then you should use a feature of the new C++ standard (C++11) called "delegating constructors" which allow you to call upon another constructor (or "delegate" the construction to another constructor). As so:

class ClassX {
private:
    int knit;
    int perl;
public:
    ClassX();
    ClassX(int);
};

ClassX::ClassX() // default ctor
: ClassX(6)  // "delegating constructor" call, since C++11
{
}
ClassX::ClassX(int warp)
: knit(warp/2), perl(warp)
{
}

Ah! Forgot about that new feature, although just how many current compilers support the full C++11 standard? In a few years when it is more widely supported, then using delegated constructors will make sense. At this point, I think that most server-level systems (RHEL 5 and 6 for example) will not be that up-to-date. Anyway, thanks for pointing it out. I read about it in an article sometime in the past year or so, but not using it, I forgot about it.

OK. But i want to know if you can manually call a constructor without object instantiation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.