Dear all,
I'm starting to get the hang of this C++ business, but I have one question that I just realized I don't have an answer to. Suppose I want to call a constructor from within a constructor to reduce redundancy in the parts that are identical. I seem to have trouble doing this. I can't find any way to do it to the right after a ':' that compiles, and if I call it directly within the constructor, I get a crash when I run the program. I have found a work around which is to call a separate function that is an initialization function from within the constructors, but I'd like to know whether there is a way to do it with constructors themselves or if that idea is simply wrong or not the way C++ was intended to be organized.
Thanks,
Sean

Dani AI

Generated

Short answer: is right that base-class construction belongs in the derived constructor's initializer list, and was right to recommend a separate init/factory approach pre-C++11. Since 2011, C++ added a cleaner option: delegating constructors let one constructor reuse another in the same class without copy-paste or a separate init method.

A minimal delegating-constructor example (C++11+):

struct Widget {
    Widget(int a, int b) : a_(a), b_(b) { /* full initialization */ }
    Widget() : Widget(0, 0) { /* delegates to the two-arg ctor */ }

private:
    int a_;
    int b_;
};

Key rules and gotchas to keep in mind:

  • A delegating constructor hands off responsibility for base-class and member initialization to the target constructor; its own mem-initializers (other than the delegation) are not applied. See the delegating-constructors section for details: delegating constructors.
  • Members are initialized in the order they are declared in the class, not the textual order of the initializer list. That can produce subtle bugs if you rely on initializer order: order of initialization.
  • Do not rely on virtual dispatch inside constructors or destructors; virtual calls behave as if the dynamic type is the type currently being constructed or destroyed. If the logic needs derived-class behavior, use a post-construction step (factory or explicit init). See details on virtual calls during construction: virtual functions and construction.

Practical guidance: prefer delegating constructors or default member initializers to remove duplication. If compiling with an older compiler, use a private init() or factory as suggested. Avoid trying to "call a constructor like a normal function" — that’s not how constructors work and leads to lifetime/ownership problems; use placement-new only when you really understand object lifetime rules.

Recommended Answers

All 3 Replies

If the code below illustrates your question, then yes, it is possible, even necessary for us to call the constructor in the initializer-lists from the subclass.

class Base
{
	public:
		Base(std::string text, int blah) : mText(text), mBlah(blah) { /* ... */ }
		
		// Some other methods

	private:
		std::string mText;
		int mBlah;
};

class Extension : public Base
{
	public:
		Extension(std::string text, int blah, std::vector<int> list)
			 : Base(text, blah), mList(list)
		{ /* ... */ }
	
		// Other methods

	private:
		std::vector<int> mList;
};

Hope this helps!

First read this, then this, and finally this.

I'm not sure I fully understand what you are trying to do (can you show some pseudo-code).

If you are trying to simply re-use the code to do the initialization of the class, then, of course, a separate initialization method (function) would do the trick, or default arguments to the constructor can also achieve this, if applicable. NOTE: do not attempt to make the initialization method virtual, this will crash your application (read the third link I posted).

If you are trying to literally call another constructor, for whatever reason, within another constructor. Forget it. That's not possible and for good reason. It might be possible with some very convoluted and dirty hack, but that's hard because it should never be done for any reason. In other words, if you are clever enough to be able to implement this kind of a dirty hack, you should be clever enough to find a way to avoid needing to.


In general, the usual idiom to use in this kind of case is the "factory function" idiom. This means you make a static method that wraps the "new" call for the class and also includes a post-constructor initialization function. This allows you for example to make the constructor private and enforce the construction through the factory function instead. By convention, people call that static method "Create", as in the following:

class Base {
  protected:
    virtual void Initialize() = 0;
  ..
};

class Derived : public Base {
  private:
    Derived() : ... { ... };
  protected:
    void Initialize() { ... };
  public:
    //This is the factory function
    static Base* Create() { 
      Base* result = new Derived;
      result->Initialize();
      return result;
    };
    //Or even better, this idiom goes very well with smart pointers:
    static std::TR1::shared_ptr<Base> Create() { 
      std::TR1::shared_ptr<Base> result = std::TR1::shared_ptr<Base>(new Derived);
      result->Initialize();
      return result;
    };
};

Great answers! I've got it now--thanks!

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.