views:

91

answers:

3

I have a class called Foo with a constructor that needs arguments, and a other class Bar with a Foo private variable

 class Foo 
 {
      public:
      Foo(string);
 }

 class Bar
 {
      public:
      Bar() { this->foo = Foo("test") }

      private:
      Foo foo;
 }

However, when I try to compile this, I get a compile error that there is no Foo::Foo() constructor. It looks like the private variable foo in class Bar gets initialized before getting a value assigned in the constructor.

How can I have a private foo variable that waits to gets initialized in my constructor?

+7  A: 

You need to use an initializer list. If you don't, your code will call the default constructor for that object.

Bar::Bar() : foo("test") {
   // stuff
}
orangeoctopus
Great, will try it.
Peterdk
yep, it worked.
Peterdk
+6  A: 

Use an initializer list:

Bar() : foo("test") {}

BTW, in C++ reasons to use this-> are rare (and often indicate other problems).

Jerry Coffin
Ok, yeah, I come from java,C# and just started trying some c++. Therefor my this-> usage. :)
Peterdk
A: 

If you want it to be initialized only in the constructor, as the topic says, make it const. consts can only be initialized in constructors, and cannot be modified by methods later on.

conio