Valhalla Legends Forums Archive | C/C++ Programming | Constructor and Destructor Declarations

AuthorMessageTime
j0k3r
Why are the constructor and destructor declared outside of the header file? What are the advantages to excluding it from the header file?

[code]
1: #include <iostream.h>
2: class Cat
3: {
4: public:
5: Cat (int initialAge);
6: ~Cat();
7: int GetAge() { return itsAge;} // inline!
8: void SetAge (int age) { itsAge = age;} // inline!
9: void Meow() { cout << "Meow.\n";} // inline!
10: private:
11: int itsAge;
12: };
[/code]

[code]
1: // Demonstrates inline functions
2: // and inclusion of header files
3:
4: #include "cat.hpp" // be sure to include the header files!
5:
6:
7: Cat::Cat(int initialAge) //constructor
8: {
9: itsAge = initialAge;
10: }
11:
12: Cat::~Cat() //destructor, takes no action
13: {
14: }
15:
16: // Create a cat, set its age, have it
17: // meow, tell us its age, then meow again.
18: int main()
19: {
20: Cat Frisky(5);
21: Frisky.Meow();
22: cout << "Frisky is a cat who is " ;
23: cout << Frisky.GetAge() << " years old.\n";
24: Frisky.Meow();
25: Frisky.SetAge(7);
26: cout << "Now Frisky is " ;
27: cout << Frisky.GetAge() << " years old.\n";
28: return 0;
29: }[/code]

April 10, 2004, 2:35 PM
Eibro
*shrug* the same reason any other functions are defined outside their respective header files.
April 10, 2004, 3:49 PM
Adron
Some compilers may generate more than one instance of a function if it's defined in the header file. The function may also always be inlined. If the function is not defined in the header file, it mostly can't be inlined.
April 11, 2004, 12:26 AM

Search