2012年2月3日 星期五

More constructor questions and answers


More constructor questions and answers

Should you write a Constructor?
Yes

What if you don't write a constructor?
Your compiler will write one for you

Why won't this compile?

1      class xyz {
2          int x;
3        public:
4         xyz(int _x) { x = _x; }
5      };
6     
7      int main() {
8        xyz Object;
9        return 0;
10      }


The xyz declaration in main() would use a default constructor. If you write any constructor in your class, your compiler will not write a default constructor for you.

Why should you write a copy constructor?
It is often desirable to create an object by copying an existing object. And even if you don't do that, anytime an object is passed or returned by value, the copy constructor is used.

What happens if you don't write a copy constructor?
If you don't your compiler will write one for you when needed. It may not do what you want.

What's the general advice about writing constructors?
Write a default constructor, a copy constructor and any others you may need. Even if you don't need the default or copy constructor now, you may need it later.

What if a class contains another class object, will the contained object's constructor be called when a container class object is declared?
Yes

沒有留言:

張貼留言