C++ Programming - Objects and Classes - Discussion

Discussion Forum : Objects and Classes - Programs (Q.No. 1)
1.
What will be the output of the following program?
#include<iostream.h> 
class Bix
{
    public:
      int x;
};
int main()
{
    Bix *p = new Bix();

    (*p).x = 10;
    cout<< (*p).x << " " << p->x << " " ;

    p->x = 20;
    cout<< (*p).x << " " << p->x ;

    return 0;
}
10 10 20 20
Garbage garbage 20 20
10 10 Garbage garbage
Garbage garbage Garbage garbage
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
4 comments Page 1 of 1.

Rahul said:   1 decade ago
@Venkatraman, shivya.

bix *p - represents pointer(p) to a class(bix) in the same way as int *p(i.e, pointer(p) to an int) is declared.

bix *p= new bix();
This is just to invoke bix class constructor with p as a pointer to that (bix) class type .

Now (*p).x is the same as p->x because both represents pointer to a type (i.e, in first case we have class bix and in second case it is taken as a structure ). Flashback the use of pointers in structures. Remember? no? Class is also a type of structure, the only difference is that we cannot have functions in structure and by default access specifier in structures is PUBLIC.

Nazmul said:   1 decade ago
Bix *p = new Bix(); in this *p is a pointer to the class not a regular object.

So whenever the value of the public variable changed within a class the pointer remains unchanged to that address.

So if the variable changes pointer will also take care of that.

p->x = 20; assigned by the object and still *p is pointed to that class.

So
cout<< (*p).x << " " << p->x ; will print 10 10 20 20.

Venkatarama said:   1 decade ago
PLEASE GIVE A BETTER EXPLANATION on the:

cout<<(*p).x<<""<<p->x;

Why the output is 10 10 20 20. I am not understanding (*p).x.

Please give me difference on p->x and (*p).x.

Shivya said:   1 decade ago
Please explain it in detail.

Post your comments here:

Your comments will be displayed after verification.