Click here to Skip to main content
15,900,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <iostream>
using namespace std;
class Box
{
    private:
    int length;
    public:
    void show()
   { int a;
    cout<<"Hie";}
    friend int printlength (Box); //friend function
};
int printlength (Box b)
{
    b.length +=10;
    return b.length;

}
int main()
{
    Box b;
    cout<<"length of box:"<<printlength (b)<<endl;
    return 0;
}


What I have tried:

C++
#include <iostream>
using namespace std;
class Box
{
    private:
    int length;
    public:
    void show()
   { int a;
    cout<<"Hie";}
    friend int printlength (Box); //friend function
};
int printlength (Box b)
{
    b.length +=10;
    return b.length;

}
int main()
{
    Box b;
    cout<<"length of box:"<
Posted
Updated 14-Feb-22 10:13am
v2

Simple: you don't initialise any values.
You create an instance of a Box:
C++
Box b;
but that doesn't assign any value to length before you try to use it:
C++
Box b;
cout<<"length of box:"
Different compilers will treat this situation differently: some will zero the memory for you, others will not - so two different compilers (or even just the switches applied when it is compiled) will produce different results.

Since a box can't have no dimensions and still be a box, a default parameterless constructor is probably fairly useless and one that takes a length, depth, and height might be a better idea ...
 
Share this answer
 
In your code, the length data member is default-initialized to undeterminate value, hence, in order to have consistent outputs you have to explicitely initialize it.
See Default initialization - cppreference.com[^] (the code sample clarifies it).
 
Share this answer
 
The reason is because you have used two different compilers: the online tool and your local compiler. And in C/C++ is the value of uninitialized memory undeterminaterd., but the online compiler has added the feature of zeroing it out.
So it is doing some extra work which slows performance and costs energy in real life. That is fine for a lazy programmer but it hurds end users time and energy bill. ;-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900