Creating a class object

Apr 29, 2013 at 5:32pm
I am new to C++ and I got some problem while understanding the codes that demonstrate the creation of class objects.

I learnt that a class object (eg. class Test), can be created by
 
  Test A;

But how about this line
 
  Test A, *APtr = 0;

Is it mean that i set a Test pointer pointing to the object A i just created as well? And does the *APtr can be assigned to 0 or NULL only?

Thanks for the help.
Apr 29, 2013 at 6:02pm
So, the line:
 
Test A, *APtr = 0;


first you are creating a Test object called A (as you already knew),but
*APtr is a pointer, that can only point to Test objects.

At this very moment in the code, it is set to null (0 and null, same difference with pointers) and there is no memory allocated for this pointer;

some things you can do to APtr to allocate memory to it is:

 
APtr = &A; // now APtr is pointing to memory location of A; 


or

 
APtr = new Test(); //now you have allocated memory somewhere in your computer that can stores information for a Test object 


Now if you wanted APtr to point to the A object at declaration, this would work:
 
Test A, *APtr = &A;  //now APtr is pointer to the memory location of A 


is that what you were asking?
Apr 29, 2013 at 6:03pm
You could write for example

Test A, *APtr = &A;

Apr 29, 2013 at 6:20pm
Re Ssturges:

The problems come when I test this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

class test{
public:
	void print(){
		cout << "Printing" << endl;
	}
};

int main(){
	test A,*Aptr = 0;
	A.print();
	Aptr -> print();
	return 0;
}


But still the line
 
Aptr -> print();

gives the result. Im not sure why would it be like this.
Apr 29, 2013 at 6:28pm
There is no access to memory at address 0. Simply member function print() is called and it recieves as the first argument 'this' with value 0 that is not used.
Last edited on Apr 29, 2013 at 6:28pm
Apr 29, 2013 at 6:29pm
Thanks very much, I think I got it.
It appears that I mixed it up with the dereference concept
Last edited on Apr 29, 2013 at 6:32pm
Topic archived. No new replies allowed.