Pointer question
Hey guys, I was just wondering when using classes to obtain a name or something like that when a pointer is used how come you don't have to use the new and delete key words.
class LibBook
{
private:
char *name
public:
LibBook( char* = '\0')
void showBookName()
};
Thanks in advance.
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
Hey guys, I was just wondering when using classes to obtain a name or something like that when a pointer is used how come you don't have to use the new and delete key words.
Generally you do. Do you have a more specific example? The one you posted is not really correct. The'\0' should be 0.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
I found another example:
class Date
{
private:
char day[10];
char month[10];
int year;
public:
void set(char* day, char* month, int year);
void display(Date datem);
char* get_day();
char* get_month();
int get_year();
};
void Date::set(char* d, char* m, int y)
{
strncpy(day, d, 9);
strncpy(month, m, 9);
year=y;
}
void Date::display(Date date)
{
cout << "The day is ";
cout << date.get_day();
cout << "\nThe month is ";
cout << date.get_month();
cout << "\nThe year is ";
cout << date.get_year();
cout << endl;
}
char* Date::get_day()
{
return day;
}
char* Date::get_month()
{
return month;
}
int Date::get_year()
{
return year;
}
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
What is your question in regard to pointers about your last posted code? The functions that return a pointer to the beginning of a char array that is private? Or the function parameters that receive a pointer to the beginning of a string to copy?
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
I was just wondering with the variables such as day and month as they are pointers how come the new and delete keywords don't have to be used.
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
The day and month variables are declared to be arrays of length 10. You only need to use new and delete[] if the arrays have not been allocated yet.
Thanks for your help Dave & Dante.
Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
Hi Dave, I was under the impression that '\0' was equal to 0?
It was more of a hint not to get into the habit of writing characters to pointers and confusing NULL and'\0'.
[edit]So yes, I overstated things when I said it wasn't quite correct.
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314