473,399 Members | 3,603 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Puzzled C++ code

8
please run the following code, and kindly advise why the result is 20 instead of 10? thanks in advance
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. class A
  8. {
  9. public:
  10.     A() : i(1) {} 
  11.     int i;
  12. };
  13.  
  14. class B : public A
  15. {
  16. public:
  17.     B() : j(3) {} 
  18.     int j; 
  19. };
  20.  
  21. int f(A* p, int count)
  22. {
  23.     int total=0;
  24.  
  25.     for(int k=0; k<count; k++)
  26.     {
  27.         int temp = p->i;
  28.         p++;
  29.         cout << " k =  " << k << ", " << temp << endl; 
  30.         total += temp;
  31.     }
  32.  
  33.     return (total);
  34. }
  35.  
  36. int main() {
  37.     B b[10];
  38.     cout << f(b,10);
  39.  
  40.     return 0;
  41. }
  42.  
Apr 17 '07 #1
19 1849
r035198x
13,262 8TB
please run the following code, and kindly advise why the result is 20 instead of 10? thanks in advance

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A
{
public:
A() : i(1) {}
int i;
};

class B : public A
{
public:
B() : j(3) {}
int j;
};

int f(A* p, int count)
{
int total=0;

for(int k=0; k<count; k++)
{
int temp = p->i;
p++;
cout << " k = " << k << ", " << temp << endl;
total += temp;
}

return (total);
}

int main() {
B b[10];
cout << f(b,10);

return 0;
}
1.) Please use code tags when posting code
2.)Why don't you tell us why you expect 10 instead of 20 first?
Apr 17 '07 #2
please run the following code, and kindly advise why the result is 20 instead of 10? thanks in advance

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class A
{
public:
A() : i(1) {}
int i;
};

class B : public A
{
public:
B() : j(3) {}
int j;
};

int f(A* p, int count)
{
int total=0;

for(int k=0; k<count; k++)
{
int temp = p->i;
p++;
cout << " k = " << k << ", " << temp << endl;
total += temp;
}

return (total);
}

int main() {
B b[10];
cout << f(b,10);

return 0;
}
Try print out sizeoff(A) and sizeof(b) to see the problem ;)
Apr 17 '07 #3
yqwen
8
1.) Please use code tags when posting code
2.)Why don't you tell us why you expect 10 instead of 20 first?
1. Sorry, I am new here, didn't know the norm and everything.
2. The reason I am expecting 10 is because I thought (still think) that for the array of b, data member i should equal 1 for every element, so the summation of such should turn out to be 10. I know something is wrong but I cannot figure out what that is.

thank you very much.
Apr 17 '07 #4
yqwen
8
Try print out sizeoff(A) and sizeof(b) to see the problem ;)
I am sorry but are you trying to help? I hope you can understand that I am pretty puzzled by this problem.
Apr 17 '07 #5
Banfa
9,065 Expert Mod 8TB
I am sorry but are you trying to help? I hope you can understand that I am pretty puzzled by this problem.
I can understand that because LaneWolf's clue is rather oblique however it is at the root of the problem.

Examine these 2 lines of your code

Expand|Select|Wrap|Line Numbers
  1.     p++;
  2.     cout << " k = " << k << ", " << temp << endl; 
  3.  
The first is the line that is manifesting the error (that is causing the error to be apparent, the actual error is a little more fundamental), can you explain what you thing it is doing? Do you understand how pointer arithmetic works in C++?

The second line is outputting data that should give you a clue as to what is going wrong.
Apr 17 '07 #6
yqwen
8
Thanks.

1. This is a question from an online C++ aptitude test.
2. I understand that array should not be used in a polymorphism setting.
3. I just wanted to know why it still produces a seemingly OK result, which happens to be the correct choice in the test. (I mean no matter how absurd it is, it still follow some logic to produce 20, so I wanted to know why it's 20)


I can understand that because LaneWolf's clue is rather oblique however it is at the root of the problem.

Examine these 2 lines of your code

Expand|Select|Wrap|Line Numbers
  1.     p++;
  2.     cout << " k = " << k << ", " << temp << endl; 
  3.  
The first is the line that is manifesting the error (that is causing the error to be apparent, the actual error is a little more fundamental), can you explain what you thing it is doing? Do you understand how pointer arithmetic works in C++?

The second line is outputting data that should give you a clue as to what is going wrong.
Apr 18 '07 #7
Ganon11
3,652 Expert 2GB
Each time the statement p++ is executed, p is set to point to some spot in front of the previous spot. The difference between the old and new address is determined by the size of the object type p points to. Since the function tells us p points to an object of type A, it assumes the only data member included is i (an integer), and increments p by the proper amount (1 byte, the size of an integer).

p really points to an object of type B, which has 2 integers; thus taking up twice the room of A. So when p is incremented 'to a new A object', it is really pointing to the B portion of that object - that is, the memory which the compiler assumes to be an A object is actually a B object. Since both classes have only one integer data member, you are able to access j as if it were an i in an A object.

Thus, you are actually adding both i and j from the first five B objects in your array with this function.

Some of my explanation is probably incorrect regarding the specifics of how each object is stored in memory, in which case I'm sure Banfa will be glad to help out. However, this is my analysis of the output you are getting.
Apr 18 '07 #8
Banfa
9,065 Expert Mod 8TB
Some of my explanation is probably incorrect regarding the specifics of how each object is stored in memory, in which case I'm sure Banfa will be glad to help out. However, this is my analysis of the output you are getting.
No need, you have it pretty much spot on.
Apr 18 '07 #9
yqwen
8
Ganon11:

Thank you very much for the clarafiction and I admire your patience and time for putting up the words. The concept is now crystal clear to me.

-yqwen


Each time the statement p++ is executed, p is set to point to some spot in front of the previous spot. The difference between the old and new address is determined by the size of the object type p points to. Since the function tells us p points to an object of type A, it assumes the only data member included is i (an integer), and increments p by the proper amount (1 byte, the size of an integer).

p really points to an object of type B, which has 2 integers; thus taking up twice the room of A. So when p is incremented 'to a new A object', it is really pointing to the B portion of that object - that is, the memory which the compiler assumes to be an A object is actually a B object. Since both classes have only one integer data member, you are able to access j as if it were an i in an A object.

Thus, you are actually adding both i and j from the first five B objects in your array with this function.

Some of my explanation is probably incorrect regarding the specifics of how each object is stored in memory, in which case I'm sure Banfa will be glad to help out. However, this is my analysis of the output you are getting.
Apr 18 '07 #10
Atli
5,058 Expert 4TB
... (1 byte, the size of an integer) ...
Hi. This is probbly a stupid question but...
An integer is 1 byte in C++? Dont bytes have a max value of 255?
Apr 18 '07 #11
Banfa
9,065 Expert Mod 8TB
An integer is 1 byte in C++?
No at least 2 bytes actually I assume that's a typo on Ganons part.

Dont bytes have a max value of 255?
No it depends on how many bits are in the byte (which is not fixed by the standard).
Apr 19 '07 #12
Atli
5,058 Expert 4TB
Ahh ok I see, thats a stupid thing not to have a fixed standard for.
Apr 19 '07 #13
Banfa
9,065 Expert Mod 8TB
Ahh ok I see, thats a stupid thing not to have a fixed standard for.
No it's not, if your platform is 7 bit or 9 bit having your programming language fixed to 8 bit bytes would be a stupid thing to do (oh and 7 and 9 bit platforms do exist).

You are falling into the trap (and TBH so do most people) of assuming that all platforms share the same characteristics as the platforms(s) you use.
Apr 19 '07 #14
Ganon11
3,652 Expert 2GB
No at least 2 bytes actually I assume that's a typo on Ganons part.
Yeah, dont know what I was thinking when I typed that. Thanks for the catch on that one.
Apr 19 '07 #15
Atli
5,058 Expert 4TB
You are falling into the trap (and TBH so do most people) of assuming that all platforms share the same characteristics as the platforms(s) you use.
Yea thats true, we (humas in general) have a habit of assuming that what we dont know doesn't exist.

No it's not, if your platform is 7 bit or 9 bit having your programming language fixed to 8 bit bytes would be a stupid thing to do (oh and 7 and 9 bit platforms do exist).
What I dont understand is why have 7 and 9 bit computer systems. I've always thought computer systems were built arround 2 in the power of x (or n)... how does 7 or 9 fit into that pattern?
Apr 19 '07 #16
JosAH
11,448 Expert 8TB
What I dont understand is why have 7 and 9 bit computer systems. I've always thought computer systems were built arround 2 in the power of x (or n)... how does 7 or 9 fit into that pattern?
They don't and why should they? PDP/8 -> 12 bit words, PDP/9 -> 9 bit bytes,
IBM/370 -> 36 bit words but variable, Cray -> ditto, Saturn -> 4 bit bytes. The
extra bits can come in handy you know; e.g. the first LISP implementations
couldn't live without them ;-)

kind regards,

Jos
Apr 19 '07 #17
Atli
5,058 Expert 4TB
Good point. Never acctually had to use any of this so I've forgotten most of it.
Also might have helped if I had been paying attention when I was learning this stuff :P
Apr 19 '07 #18
Banfa
9,065 Expert Mod 8TB
What I dont understand is why have 7 and 9 bit computer systems. I've always thought computer systems were built around 2 in the power of x (or n)... how does 7 or 9 fit into that pattern?
7, 9, 12 and anything else you care to mention fits the pattern because they are the x value.

The power of 2 thing comes into maximum integer values and bit values, for instance on an 8 bit machine the bits have the values

1 2 4 8 16 32 64 128 maximum unsigned char = 256

all powers of 2, the equivalent values for 7 and 9 bits are

7: 1 2 4 8 16 32 64 maximum unsigned char = 128
9: 1 2 4 8 16 32 64 128 256 maximum unsigned char = 512

x can be anything you want, but everything else will be a power of 2 due to the binary nature of computers. (actually even this is not quite true).
Apr 19 '07 #19
Atli
5,058 Expert 4TB
Ahh I see, its all coming back to me now :P

Thanks.
Apr 19 '07 #20

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

Similar topics

5
by: Maciej Nadolski | last post by:
Hi! I`ve got a simple question but I`m puzzled:( When I create variable: for example $query for query to MySQL its obvieus that I want to use variables. Now should I do something like that: 1)...
7
by: Robin Becker | last post by:
We've been queried about the randomness of some filenames we're producing. I worked through and seemed to satisfy myself that random is being initialised from the system time in C time(&now)...
0
by: Frank L | last post by:
Greetings, I am somewhat puzzled by a difference that occurs when I compile my web application out of VS.NET or if I compile it through NAnt. The issue is with how the resources get compiled into...
4
by: EvelynAnd Ethan | last post by:
Hi, ItemCommand event not firing from a dynamic user control ,WHERE A DATAGRID HAS BUTTON,when i click on the linkbutton first time the itemcommand event doesnt fire,second time event fires up ...
0
by: alexandre_irrthum | last post by:
Hi there, I am puzzled by the comportment of the line function from the ImageDraw module with regard to the way it draws or does not draw the last pixel of a line. Below I test this function...
6
by: =?Utf-8?B?QkJN?= | last post by:
Hi, I have an app that is crashing due to a System.ArgumentException. At this point it's just a simple app to test some basic object values. The main app is a Windows App that looks like...
5
by: intrader | last post by:
The code is: <code> namespace ConsoleApp { public interface Ivalidator{ String ErrorMessage{get;} Boolean IsValid{get;} void Validate(string value,long mask, long maxLength,string...
7
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class...
16
by: Herb | last post by:
I am new to vb.net coming from vb6 I built and published an app that work fine on the production machine. I try installing it on a clean machine and I installed NETFramework2.0.50727 ( i am...
15
by: Lorenzo Stella | last post by:
Hi all, I haven't experienced functional programming very much, but now I'm trying to learn Haskell and I've learned that: 1) in functional programming LISTS are fundmental; 2) any "cycle" in FP...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.