Abhineet
Abhineet

Reputation: 6617

Instance of c++ class

In the below code what does "a" and "&a" contains?

class list{
};
int main(){
    list *a= new list();
    cout<<"\n Values:a="<<a<<" & &a="<<&a<<endl;
    return 0;
}

Upvotes: 0

Views: 182

Answers (6)

Joris Timmermans
Joris Timmermans

Reputation: 10968

a is a pointer to an object of type list.

&a is the address of the pointer a.

Upvotes: 5

Stephan
Stephan

Reputation: 4247

Writing the & left to a variable gives you the address of this variable. This is essentially the same as a pointer to the potion of memory, this variable is stored in.

Since a is already a pointer, &a is a pointer to a pointer.

So in your example a contains the memory address of a list as a numeric value. &a is also a numeric value, which contains the memory address, where the pointer a is stored.

Upvotes: 2

Vijay
Vijay

Reputation: 67211

a is a pointer to the object list which is allocated on heap. basically a contains an address(pointer stores an address,if you are aware). And &a does not contain anything.what you are doing is actually taking the address of that pointer and printing it.

Upvotes: 2

iammilind
iammilind

Reputation: 69968

a is pointer to the list object (allocated generally in free-store). Content of a is changeable.

&a is address of a (where a resides in memory layout). &a is not changeable.

Upvotes: 2

Alok Save
Alok Save

Reputation: 206508

a is a pointer to an object of type list dynamically allocated on freestore(heap)
&a is the address of the pointer.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153899

a contains a pointer to the object you newed, and &a doesn't contain anything, since it's not an object (lvalue, in C++ parlance), just an expression.

Upvotes: 1

Related Questions