thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

C++ Constructor does not see the member of a member object

I have met a strange case: I have an object that have some string members, that I use to initialize some other members like here:

class A
{
private:
   B b;
   C c1;
   C c2;

public:
   A(const string& str) : b(str), c1(b.foo1()), c2(b.foo2()) {}

// ...
};

class B
{
public:
   B(const string& str)
   { 
      // ... 
   }
   string& foo1()
   {
      string s1;
      // initialization
      return s1;
   }
   string& foo2()
   {
      string s2;
      // initialization
      return s2;
   }
};
class C
{
private:
   string s;
public:
   C(const string& str) : s(str) {}
};

When I call the constructor of A:

string str = "some string here";
A(str);

I get the following error:

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::replace

the problem is here:

A(const string& str) // str == "some string here"
   : b(str),         // enters the B(str), str == "some string here"
     c1(b.foo1()),   // enters the C(str), str the string that I want
     c2(b.foo2())    // enters the C(str), but str is not visible

How would you suggest me to do it?

Upvotes: 0

Views: 64

Answers (2)

harmic
harmic

Reputation: 30597

You are returning references to local variables in both foo1 and foo2. These variable are limited in scope to the body of the functions in which they are defined. They disappear as soon as the function returns, so attempts to reference them after this cause your program to crash.

Upvotes: 2

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 71019

You are returning a reference to a local variable in foo1 and foo2(s1 and s2 respectively) this is not allowed and using the reference will invoke undefined behavior.

Upvotes: 4

Related Questions