简体   繁体   中英

How can you call a c++ constructor somewhere other than where you define a variable without calling new?

I have a class set up like this:

class Foo {
  Foo();    

  private:
     Bar m_bar;
}

That is the class definition in it's own header file, and now in the source file to go with it I have the constructor and I tried doing this:

Foo::Foo() {
  m_bar("parameters for the Bar constructor");
}

However this doesn't work and gives me an error. I can make m_bar a pointer and then in Foo's constructor do this:

m_bar = new Bar("parameters here");

However that makes m_bar a pointer and I don't want that.

I'm not the best with C++ classes and pointers, so could something either explain a way for me to have m_bar defined in the Foo class but constructor somewhere else or if it is better to make m_bar a pointer in this situation explain why? While I would rather not make it a pointer(because I don't understand pointers extremely well), if that is the best way to do it then I would rather do it that way, but I'd still like someone to explain why that is the best way to do it(if it is).

Yes, using the initializer list syntax:

Foo::Foo() : 
  m_bar("parameters for the Bar constructor")
{
}

You need to use initialization lists:

Foo::Foo() :
m_bar("and you ought to check out a good C++ book :)")
{
    // Book list: http://tinyurl.com/so-cxxbooks
}

如果我理解正确,则可以使用构造函数初始化列表进行操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM