You are here:

C++/Just tell me y this code works:...

Advertisement


Question
Just tell me y this code works: -
class A
{
   int a;
public:
   void display()
{
cout<<a;
}
};
int main()
{
A *ab;
ab->display();
return 0;
}
OUTPUT :
<a>
displays the value of a.
.....
Now, if we print the value of ab it is NULL.
Then how it can print the value of a.

Answer
Hello!
Thanks for your question.
Aashish, i don't get the clear idea, what you are
trying to understand in this program. See it works
like this,

You have a class names 'A', which has a single private
variable a. It has a public fuction, display() which
shows the value of a. Firt of all, you havent described
the constructor of 'A', and a is not initlized so it
will contain the garbage value.

Then you declare an object of class 'A', which is
basically a pointer, it contains the address of
variable 'a'. Try the statements like.

cout<<&a<<endl;// use this in display function
cout<<ab<<endl; //try this in main

Both will show the same address which means that
ab is currently pointing towards the memory location
of 'a'. It doesnt display null value. If you have
any more queries , don't be afraid to ask.
I hope this helps.
Regards
Professional  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Professional

Expertise

I can answer any question about functions,pointers,structures,object oriented programming basics of classes and data structures.My strong field is structured programming.

Experience

I have got 2 years experiece under C . I am able to answer about the structured concepts pointers to a little extent,OOP concepts. I have also experience in data Strucutres like Linked List, Stacks , Queues, Heaps, B Trees, Red Black Trees. I will try to satisfy with my knowledge. I am the Student of an expert here Martin, what i have learnt today, i just owe my every knowledge to him. He is the greatest.

©2016 About.com. All rights reserved.