You are here:

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


Just tell me y this code works: -
class A
   int a;
   void display()
int main()
A *ab;
return 0;
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.

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.


All Answers

Answers by Expert:

Ask Experts




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


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.

©2017 All rights reserved.