Understanding variables scope and function calling

Hi all,
look at this code:

File A.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#ifndef A_H_
#define A_H_

#include <string>
using namespace std;

class A {
public:
A();
virtual ~A();

char* getString();
string getString2();

void print();
};

#endif /* A_H_ */ 


File A.cpp:
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
#include "A.h"
#include <iostream>

A::A()
{
}

A::~A()
{
}

char* A::getString()
{

char tmp[10];
memset(tmp, '\0', 10);
sprintf(tmp, "Example");
return tmp;
}

string A::getString2()
{

string tmpStr("Example ");
return tmpStr;
}

void A::print()
{
cout<<"getString(): "<<getString()<<endl;
cout<<"getString2(): "<<getString2()<<endl;
}


Ok, when I call function print() on A, this is the output:
getString(): �����
getString2(): Example


I know that getString() method can't work, because memory reserved for local variable tmp will be cleaned at the end of the function; but why getString2() works right? Is not tmpStr a local variable like tmp?

Thanx
When you return a string, C++ uses its copy constructor to copy the returned object (tmpStr) and a copy is given to the caller (A::print()). The copy is discarded for sure when the scope is gone.
Last edited on
Yes, but strings are objects, and thus the copy constructor is called. That will copy the data correctly. char arrays are not, and thus you only "copy" the address (which like you said, is garbage).
Topic archived. No new replies allowed.