473,659 Members | 2,920 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About references in C++.

78 New Member
Hi all. I'm currently learning C++ from a tutorial C to C++. I have a question on references. More precisely, i'm confused why this code gives the following result.
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4.  
  5. class person
  6. {
  7. public:
  8.  
  9.    char *name;
  10.    int age;
  11.  
  12.    person (char *n = "no name", int a = 0)
  13.    {
  14.       name = new char[100];
  15.       strcpy (name, n);
  16.       age = a;
  17.    }
  18.  
  19.    person (person &s)               // The COPY CONSTRUCTOR
  20.    {
  21.       name = new char[100];
  22.       strcpy (name, s.name);
  23.       age = s.age;
  24.    }
  25.  
  26.    ~person ()
  27.    {
  28.       delete [] name;
  29.    }
  30. };
  31.  
  32. void foo(person p)
  33. {
  34.    cout << p.name << ", age " << p.age << endl << endl;
  35. }
  36.  
  37. person &bar()
  38. {
  39.     return person("Todd", 15);
  40. }
  41.  
  42. int main ()
  43. {
  44.    person k ("John", 56);
  45.    cout << k.name << ", age " << k.age << endl << endl;
  46.  
  47.    foo(k); 
  48.  
  49.    person m(k);
  50.  
  51.    person n = bar();
  52.     foo (n);
  53.  
  54.    return 0;
  55. }
  56.  
result:
------------------------------------------------------
C:\Documents and Settings\Sebouh >C:\my_cpp_test s\cpp_test\debu g\cpp_test.exe
John, age 56

John, age 56

John, age 4212483 <----------------- WHY??
-----------------------------------------------------

why not Todd?


Thanks
Apr 15 '07 #1
4 1026
JosAH
11,448 Recognized Expert MVP
Your function bar attempts to return a reference to a local variable of type person.
After functions have returned all local variables have gone and destructed so your
reference refers to garbage.

kind regards,

Jos
Apr 15 '07 #2
Sebouh
78 New Member
So is it "by chance" that i get John?
Apr 15 '07 #3
JosAH
11,448 Recognized Expert MVP
So is it "by chance" that i get John?
Yep, the memory where that object resided on the stack is gone, it's no more,
it's pushing up the daisies, it shuffled off its mortal coil, it's gone to meet its
maker ;-) The content of that memory could be anything.

kind regards,

Jos
Apr 15 '07 #4
Sebouh
78 New Member
Yep, the memory where that object resided on the stack is gone, it's no more,
it's pushing up the daisies, it shuffled off its mortal coil, it's gone to meet its
maker ;-) The content of that memory could be anything.

kind regards,

Jos
Heh, alright then.
Thanks.
Apr 15 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

7
1577
by: Snake | last post by:
Hi guys, I have question about classes. when u create class called Test. and you define variable Test c; so does this act like( a variable c of type Test pointing to an abject )? The thing that I am confused with java where you say Test c = new Test; whre you can move this Test object around by saying "Test b" and then b = c;(so c and b points to the same object). while in c++ I think it has different meaning(like b would have different...
21
2107
by: JustSomeGuy | last post by:
When you iterate through a list of objects in a list. list<object> mylist; list<object>::const_iterator iter; object ob; for (iter=mylist.begin(); iter != mylist.end(); ++iter) { ob = *iter; ob.value = 10;
6
2480
by: Andreas | last post by:
Hello list, what about uniqueness of inherited primary keys ? eg you have : create table objects ( id int4, date_created timestamp(0), primary key (id)
24
2107
by: venkatesh | last post by:
hai, any can tell what is the advantge of using pointers?any increase in speed or execution time? if you know please tell what are the real time applications of data structure? thanks in advance
3
5758
by: MIGUEL | last post by:
Hi all, I'm quite lost with how adding web references to a project creates proxy classes. I've developed a web service with two classes inside and that contains three references to three DLLs. After building it up, I've deployed it on the web server. From my Windows application, I then add a web reference to that web service.
10
3710
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
2
2119
by: jodyblau | last post by:
I have noticed that when I move my database onto a different computer, I often get a message about some reference missing. So I go into the reference list, and find the one that says "Missing," and I uncheck it. Everything appears to work fine after that, however, this raises two questions in my mind. 1. Does simply unchecking the missing reference cause me to lose any functionality? I haven't noticed any yet, but that doesn't mean...
75
5431
by: Steven T. Hatton | last post by:
No, this is not a troll, and I am not promoting Java, C-flat, D, APL, Bash, Mathematica, SML, or LISP. A college teacher recently posted to this newsgroup regarding her observation that there has been a significant decline in the number of students opting to take courses in C++. I just want to let people know what I believe are the biggest obstacles to C++ language acquisition, and what aspects of the language make it less appealing than...
35
1905
by: rebeccatre | last post by:
hi can Variant archiving setTimout('.. capability be done without using it? :-)
5
1261
by: campyhapper | last post by:
I've seen this in C++, not Objective C: namespace bar { struct foo { foo (int a, int b) : int a_, int b_ {} }; }
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8335
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8747
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.