-
member pointer
Hello there peoples! How are ya! Can anyone here help me with a little problem I have?
I am trying to create class with a member pointer, but when i try to dereference it the program crashes, but i dont get any error message from the compiler. Here is the code:
Code:
class TEST
{
public:
Test(); //constructor
int GetAge () const;
void SetAge (int age);
private:
int * pAge;
};
TEST::Test()
{
int * pAge = new int;
}
void TEST::SetAge(int age)
{
*pAge = age;
}
this is the class, constructor and function. When i try to set age i get error. Can anyone help me?
-
Code:
TEST::TEST()
{
pAge = new int;
}
Should work like that. Remember case sensetivity, Test should be TEST for the constructor.
[edit]Also should be capitalized properly in the definition of the class above.[/edit]
-
The reason is C++ is case-sensitive. TEST is different from Test, and consequently, Test is not the constructor of TEST, which means you never call "new int" before trying to set it.
The compiler should warn you about the function "Test" having no return type, though...
** edit **
Rats... beaten to it!
-
sorry about the mistype...it actually is
TEST::TEST
-
>>sorry about the mistype...it actually is
Then your problem is the second problem. The first being a typo, the second being a local variable hiding the class member.
Code:
int * pAge = new int;
should be
-
great tx!,
i will do it and get back to ya!
-
By the way, looks like you may need a custom destructor to avoid the potential memory leak:
Code:
TEST::~TEST()
{
delete pAge;
}
-
And a custom copy constructor and assignment operator, as well.