Creating a class object
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
But how about this line
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.
So, the line:
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;
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?
You could write for example
Test A, *APtr = &A;
The problems come when I test this
using namespace std;
cout << "Printing" << endl;
test A,*Aptr = 0;
Aptr -> print();
But still the line
gives the result. Im not sure why would it be like this.
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
Thanks very much, I think I got it.
It appears that I mixed it up with the dereference concept
Last edited on
Topic archived. No new replies allowed.