![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Hobbyist Programmer
|
Constructor/destructor
I am having problems with constructors and destructors. Could someone please explain them? Like the example. Say I have a class called Cat. How do I declare a new constructor
__________________
And there was much rejoicing... Yay.... |
|
|
|
|
|
#2 |
|
Professional Programmer
|
Cat();
and ~Cat(); |
|
|
|
|
|
#3 |
|
Hobbyist Programmer
|
... Wtf is that?
__________________
And there was much rejoicing... Yay.... |
|
|
|
|
|
#4 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
Like this:
class Cat {
char name[32];
short age;
char owner[32];
Cat() {
// constructor
name[0] = '\0'; // this is an quick way to clear a string
age = 0;
owner[0] = '\0';
}
Cat(char *cat_name, int cat_age, char *cat_owner) {
// this is another constructor - you can have more than one
// this one lets the user specify the info in the declaration
strcpy(name, cat_name);
age = cat_age;
strcpy(owner, cat_owner);
}
~Cat() {
// destructor - clean up in here
}
}
int main() {
Cat my_cat;
strcpy(my_cat.name, "Fluffy");
my_cat.age = 3;
strcpy(my_cat.owner, "Me");
Cat your_cat("Tibbles", 4, "You");
} |
|
|
|
|
|
#5 | |
|
Hobbyist Programmer
Join Date: Dec 2004
Location: a cardboard box
Posts: 118
Rep Power: 4
![]() |
Quote:
__________________
... |
|
|
|
|
|
|
#6 | |
|
Professional Programmer
|
Quote:
|
|
|
|
|
|
|
#7 |
|
Programmer
Join Date: Feb 2005
Posts: 89
Rep Power: 4
![]() |
the best way to get it is to make these silly output notices for yourself.
cat(int number) { cout<<"you just made cat number"<<number<<endl; } ~cat() { cout<<"you just killed cat number"<<number<<endl; } i ALWAYS do this, until i'm absolutely positive that my memory crap is working |
|
|
|
|
|
#8 |
|
Hobbyist Programmer
|
I think I understand...ARRGHHH! C++ is so confusing.
__________________
And there was much rejoicing... Yay.... |
|
|
|
|
|
#9 |
|
Hobbyist Programmer
|
Constructors basically let you interface with the class the moment you declare an object for the class.
Destructors basically clean up the shit that's left over from the other member functions of the class. So if one member function Allocates a bit of memory, the destructor can delete the memory. It seems hard to grasp at first but it can save you quite a bit of code. I should also note, Constructors and Destructors never have return values. Constructors just let you interface with member variables and other things involving the class. Destructors just get rid of the shit that's left to pick up. |
|
|
|
|
|
#10 |
|
Hobbyist Programmer
|
kk...thanks to all that helped. I am pretty sure I got it. Thanks.
__________________
And there was much rejoicing... Yay.... |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|