For loops causing bad allic char* error

The compiler keeps giving me bad alloc errors re a char pointer that isnt in the program.
Please advise

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream>
#include<cstring>
#include<string>

using namespace std;

	class text
	{
		public:
		string address = addr;
		void getaddr(int);
	    void putaddr();
		private:
		string addr;
	};
	
	void text :: getaddr(int i)
	{
		cout <<"Enter the 1st line of address " << i+1 << " \n\n";
	
	getline(cin,address);
	cout <<"\n";
	}
	
	void text :: putaddr()
	{
		cout << "You entered " << address << "\n\n";
	}
	
	
	
int main()
{

    const int size = 3;

	text obj [size];
	
	for(int i = 0; i<size; i++)
	{
		obj[i].getaddr(i);
		obj[i].putaddr();
	}
	
}
exact message?
I suspect it is
string address = addr;

what exactly is addr (its value) upon object creation?
Last edited on
Data members of a class are constructed in the order that they're declared in the class. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

template <int n>
class A{
public:
    A(){
        std::cout << n << std::endl;
    }
};

class B{
    A<42> a;
    A<93> b;
    A<67> c;
};

int main(){
    B b;
}
The output for this program is
42
93
67

On line 10 you initialize text::address using text::addr (declared on line 14), but text::addr hasn't been constructed yet, so the memory for that future object is in an undefined state. You're basically doing this:
1
2
3
char mem[sizeof(std::string)];
//mem is uninitialized
std::string s = *(std::string *)mem;
Thanks for the help guys that really clarified :-)
Topic archived. No new replies allowed.