473,385 Members | 1,798 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,385 software developers and data experts.

Can someone please explain the output of this code?

Hi,

Can some one please explain why the output of this program is 15

#include <iostream>

using namespace std;

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

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

int f(A* p, int count)
{
int total = 0;
for(int i=0; i<count; ++i)
{
total+=p++->i;
}
return(total);

}

int main()
{
B b[11];
cout << f(b,10);
return 0;
}

Regards,

Jul 27 '07 #1
3 1384
Aarti wrote:
Hi,

Can some one please explain why the output of this program is 15
[...]
class A
[...]
class B: public A
[...]
int f(A* p, int count)
{
int total = 0;
for(int i=0; i<count; ++i)
{
total+=p++->i;
}
return(total);

}

int main()
{
B b[11];
cout << f(b,10);
return 0;
}
You invoked undefined behaviour by treating an array of Bs as array of As.

See Item 3 "Never treat arrays polymorphically" in Scott Meyers's "More
Effective C++"

--
Thomas
http://www.netmeister.org/news/learn2quote.html
Jul 27 '07 #2
Aarti <aa*********@gmail.comwrote:
Can some one please explain why the output of this program is 15

#include <iostream>

using namespace std;

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

class B: public A
{
public:
B():j(2)
{}
int j;
};
Note, sizeof(B) sizeof(A). For the sake of this explanation, let's
assume that sizeof(B) is 8 and sizeof(A) is 4.
int f(A* p, int count)
{
int total = 0;
for(int i=0; i<count; ++i)
{
total+=p++->i;
The increment above moves 'p' by sizeof(A) bytes. i.e., 4 bytes, but
since the object pointed to by 'p' is really a B, 'p' now points to the
middle of a B object.
}
return(total);

}

int main()
{
B b[11];
In the above line, you create an array of B. If sizeof(B) is 8, and b[0]
is at address location 0x0, then b[1] is at address location 0x8.
cout << f(b,10);
return 0;
}

Regards,
Jul 27 '07 #3
joe
You have exercised a big no-no. When you increment a pointer, what
you are effectively doing is adding the sizeof the pointee type to the
value of the pointer. This allows you to visit the next element of an
array automatically. What you have done here is passed an array of B-
s (which are larger than A-s) into your function and trying to access
it as though it were A-s. So, what happens is that you take your
pointer and add sizeof A to it. This means that your pointer now
points into the middle of your B object somewhere. It just so happens
that since this class is simple and nothing faults, but you are now
treating the middle of the B as another A. This is bad. It turns out
that in your example you effectivly access b[0].i + b[0].j + b[1].i +
b[1].j .... and so forth. This gives 5 * 1 + 5 * 2 = 15. Normally, I
might expect a fault if things were more complicated than simple ints
and it is definitely undefined behavior.

joe

Jul 27 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Maciej Nadolski | last post by:
Hi! I can`t understand what php wants from me:( So: Cannot send session cache limiter - headers already sent (output started at /home/krecik/public_html/silnik.php:208) in...
12
by: Sanjeev | last post by:
Output of followin program at Turbo C++ 3.0 is 7 ( Not 2 or 3). Please explain why ? //////////////////////////////////////////////// #include<stdio.h> #include<string.h> void main() {
22
by: Jaspreet | last post by:
I was recently asked this question in an interview. Unfortunately I was not able to answer it and the interviewer made a decision on my C strengths (or weekness) based on this single question and...
0
by: raa abdullah | last post by:
Overview A conflict-serializbility\recoverability checker, SCR, is a program that takes in a schedule and outputs 2 decisions: Conflict serialzable or Not confilict serializable AND Recoverable or...
1
by: td0g03 | last post by:
Hello, I am new to C and I am new to English. I not sure what palindromes mean. I don't know exactly what my teacher wants me to do. If someone could explain it to me in a different way that would be...
7
by: Mike Kent | last post by:
It's often useful for debugging to print something to stderr, and to route the error output to a file using '2>filename' on the command line. However, when I try that with a python script, all...
2
by: sathishc58 | last post by:
Hi All Please explain why strlen returns() "16" as output here and explain the o/p for sizeof() as well main() { char a={'a','b','c'}; printf("strlen=%d\n", strlen(a));...
6
by: Dave Young | last post by:
I'm looking at some code that i've inherited and I'm not really familar with what's going on here and was hoping somone could explain it to me. For reference: f1 is a long f2 is a long ...
0
by: LanaR | last post by:
Hello, one sql statement is causing severe performance issue. The problem occurs only in UDB environment, the same statemnt on the mainframe is running fine. I have an explain output from the sql....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
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?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...

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.